package com.car.web.controller.index;

import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.car.bean.GridObj;
import com.car.bean.PageObj;
import com.car.dal.dao.moneys.TgMoneyDao;
import com.car.dal.object.*;
import com.car.util.*;

import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.CellStyle;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.car.dal.dao.category.TgCategoryDao;
import com.car.dal.dao.client.TgClientDao;
import com.car.dal.dao.client.TgClientImpDao;
import com.car.dal.dao.client.TgClientPhoneDao;
import com.car.dal.dao.client.TgClientPhoneDaoImpl;
import com.car.dal.dao.department.TgDepartmentDao;
import com.car.dal.dao.from.FromUserDao;
import com.car.dal.dao.grade.TgUsergradeDao;
import com.car.dal.dao.method.TgMethodDao;
import com.car.dal.dao.office.TgOfficeDao;
import com.car.dal.dao.powers.TgPowersDao;
import com.car.dal.dao.reception.TgReceptionDao;
import com.car.dal.dao.reserve.TgReserveDao;
import com.car.dal.dao.source.TgSourceDao;
import com.car.dal.dao.state.TgStateDao;
import com.car.dal.dao.sudent.StudentDao;
import com.car.dal.dao.task.TgTaskDao;
import com.car.dal.dao.tiyanke.TgTiyankeDao;
import com.car.dal.dao.tracking.TgTrackingDao;
import com.car.dal.dao.user.UserDao;
import com.car.dal.dao.user.UserinfoDao;
import com.car.dal.dao.user.UsernamesDao;
import com.car.dal.dao.usergroup.TgUsergroupDao;
import com.car.dal.dao.vote.JsVoteDao;
import com.car.dal.dao.work.TgworkDao;
import com.car.dal.dao.workload.TgworkloadDao;
import com.car.exception.BaseException;
import com.car.util.JsonExecutor.JsonBiz;
import com.car.util.WebExecutor.Biz;
import com.car.web.controller.base.BaseController;
import com.car.web.controller.base.BaseVo;
import com.fasterxml.jackson.annotation.JsonSubTypes.Type;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;

/**
 * 登录控制
 *
 * @author Administrator
 */
@Controller
@RequestMapping("/index")
public class SystemController extends BaseController {

    private static final Logger logger = Logger.getLogger(SystemController.class);

    @Resource
    private UserDao userDao;
    @Resource
    private UserinfoDao userinfoDao;
    @Resource
    private TgOfficeDao tgOfficeDao;
    @Resource
    private TgClientDao clientDao;
    @Resource
    private TgSourceDao sourceDao;
    @Resource
    private StudentDao studentDao;
    @Resource
    private TgTrackingDao trackingDao;
    @Resource
    private TgStateDao stateDao;
    @Resource
    private TgReserveDao reserveDao;
    @Resource
    private TgPowersDao powersDao;
    @Resource
    private TgReceptionDao receptionDao;
    @Resource
    private JsVoteDao voteDao;
    @Resource
    private TgworkloadDao workloadDao;
    @Resource
    private TgUsergradeDao usergradeDao;
    @Resource
    private TgMethodDao methodDao;
    @Resource
    private TgMoneyDao moneyDao;
    @Resource
    private TgTiyankeDao  tgTiyankeDao;
    @Resource
    private UsernamesDao usernamesDao;
    @Resource
    private TgClientImpDao clientImpDao;
    @Resource
    private TgClientPhoneDao tgClientPhoneDao;
    @Resource
    private FromUserDao fromuserDao;

    //咨询师业务管理--客户预约数据管理
    @RequestMapping(value = "/system_reserve_list")
    public ModelAndView system_reserve_list(ModelMap modelMap, final BaseVo vo,final HttpServletRequest request, final HttpServletResponse response)
            throws Exception {
        modelMap = WebExecutor.execute(logger, vo, new Biz() {
            public Result process() {
                Result result = new ResultSupport(true);
                String knickname = request.getParameter("knickname");
                String snickname = request.getParameter("snickname");
                String province = request.getParameter("province");
                String phone1 = request.getParameter("phone");
                String email = request.getParameter("email");
                String qq = request.getParameter("qq");
                String source = request.getParameter("source");
                String sdate = request.getParameter("start_date");
                String edate = request.getParameter("end_date");
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

                TgReserve reserve = new TgReserve();

                if (knickname != null && !"".equals(knickname)) {
                    reserve.setKnickname(knickname);
                }
                if (snickname != null && !"".equals(snickname)) {
                    reserve.setSnickname(snickname);
                }
                if (province != null && !"".equals(province)) {
                    reserve.setProvince(province);
                }
                if (phone1 != null && !"".equals(phone1)) {
                    reserve.setPhone(phone1);
                }
                if (email != null && !"".equals(email)) {
                    reserve.setEmail(email);
                }
                if (qq != null && !"".equals(qq)) {
                    reserve.setQq(qq);
                }
                if (sdate != null && !"".equals(sdate)) {
                    try {
                        Date date = sdf.parse(sdate);
                        reserve.setStart(date.getTime() / 1000);
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }

                }
                if (edate != null && !"".equals(edate)) {
                    try {
                        Date date = sdf.parse(edate);
                        reserve.setEnd(date.getTime() / 1000);
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }

                }
                
                if (source != null && !"".equals(source)) {
                	reserve.setSource(source);
                }
                Integer currPage = 1;
                if (vo.getCurrPage() != null && !"".equals(vo.getCurrPage())) {
                    currPage = vo.getCurrPage();
                }
                Integer total = reserveDao.getReserveByTypeCount(reserve);
                Page page = PageUtil.createPage(8, currPage, total);
                List<TgReserve> list = reserveDao.getReserveByType(reserve, page);
                if (list != null && list.size() > 0) {
                    TgTracking tracking = new TgTracking();
                    Gson gson = new Gson();
                    for (TgReserve res : list) {
                        tracking.setClient(res.getClient());
                        List<TgTracking> listsize = trackingDao.findByExample(tracking);
                        res.setTracksize(listsize.size() + "");

                        if (res.getPhone() != null && !"".equals(res.getPhone())) {
                            if (res.getPhone().contains("[{")) {
                                List<Phone> phone = gson.fromJson(res.getPhone(),
                                        new TypeToken<List<Phone>>() {
                                        }.getType());
                                res.setPhlist(phone);
                            }
                        }
                    }

                }
                result.setDefaultModel("list", list);
                result.setDefaultModel("page", page);
                result.setDefaultModel("knickname", knickname);
                result.setDefaultModel("snickname", snickname);
                result.setDefaultModel("province", province);
                result.setDefaultModel("phone1", phone1);
                result.setDefaultModel("email", email);
                result.setDefaultModel("qq", qq);
                result.setDefaultModel("sdate", sdate);
                result.setDefaultModel("edate", edate);
                result.setDefaultModel("source", source);
                return result;
            }
        });
        return new ModelAndView("system/system_reserve_list", modelMap);
    }

    //删除预约数据
    @RequestMapping(value = "/system_reserve_del")
    public ModelAndView system_reserve_del(ModelMap modelMap, final BaseVo vo,final HttpServletRequest request, HttpServletResponse response)
            throws BaseException {
        modelMap = JsonExecutor.execute(logger, vo, new JsonBiz() {
            public Result process() {
                Result result = new ResultSupport(true);

                String keyname = request.getParameter("key");
                TgUser user = UserUtil.getUserFromCookies();
                if (user != null) {
                    if (keyname != null && !"".equals(keyname)) {
                        TgReserve reserve = new TgReserve();
                        reserve.setKeyname(keyname);
                        List<TgReserve> list = reserveDao.getReserveByKeyname(reserve);
                        if (list != null && list.size() > 0) {
                            reserveDao.delete(TgReserve.class, Long.valueOf(list.get(0).getId()));
                        }
                    }
                }
                return result;
            }
        });

        return new ModelAndView("", modelMap);
    }

    //咨询师业务管理--预约详情
    @RequestMapping(value = "/system_reserve_view")
    public ModelAndView system_reserve_view(ModelMap modelMap, final BaseVo vo,
                                            final HttpServletRequest request, final HttpServletResponse response)
            throws Exception {
        modelMap = WebExecutor.execute(logger, vo, new Biz() {
            public Result process() {
                Result result = new ResultSupport(true);
                String keyname = request.getParameter("keyname");
                SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
                SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String region_u = "";
                TgUser u = UserUtil.getUserFromCookies();
                TgReserve res = new TgReserve();
                res.setKeyname(keyname);
                List<TgReserve> reslist = reserveDao.getReserveByUsername(res);
                if (reslist != null && reslist.size() > 0) {
                    res = reslist.get(0);
                    for (TgReserve reserve : reslist) {
                        boolean flag = StringUtil.getHanzi(reserve.getRemark());
                        if (!flag) {
                            try {
                                byte[] bytes = StringUtil.hexDecode(reserve.getRemark());
                                String ObjContent = new String(bytes, "UTF-8");
                                res.setRemark(ObjContent);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }
                    region_u = res.getRegion();
                    List<Phone> ph = null;
                    if (res.getPhone() != null && !"".equals(res.getPhone())) {
                        if (res.getPhone().contains("[{")) {
                            Gson gson = new Gson();
                            ph = gson.fromJson(res.getPhone(),
                                    new TypeToken<List<Phone>>() {
                                    }.getType());
                        }
                    }

                    if (u.getUsername().equals("system")) {
                        res.setPhlist(ph);
                    } else {
                        if (res.getPhone() != null && !"".equals(res.getPhone())) {
                            if (u.getUsername() != null && !"".equals(u.getUsername())) {
                                String u_region = u.getRegion();
                                String region_temp = u.getRegion_temp();
                                if(region_temp==null||"".equals(region_temp)){
                                	region_temp="";
                                }
                                if (u_region.equals(region_u) || region_temp.contains(region_u)) {
                                    res.setPhlist(ph);
                                    res.setPhone(res.getPhone());
                                } else {
                                    res.setPhone("<span class=\"caption\">禁止查看</span>");
                                }
                            }
                        }
                    }
                }


                TgReserve reserve = new TgReserve();
                TgClient client = new TgClient();
                TgStudent student = new TgStudent();
                String clkeyname = "";
                if (keyname != null && !"".equals(keyname)) {
                    reserve.setKeyname(keyname);
                    List<TgReserve> list = reserveDao.getReserveByKeyname(reserve);
                    if (list != null && list.size() > 0) {
                        reserve = list.get(0);
                        clkeyname = reserve.getClient();
                        client.setKeyname(reserve.getClient());
                        List<TgClient> cliList = clientDao.findByExample(client);
                        if (cliList != null && cliList.size() > 0) {
                            client = cliList.get(0);
                            student.setPkey(client.getKeyname());
                            List<TgStudent> stuList = studentDao.findByExample(student);
                            if (stuList != null && stuList.size() > 0) {
                                for (TgStudent stu : stuList) {
                                    if (stu.getFeature() != null && !"".equals(stu.getFeature())) {
                                        boolean flag = StringUtil.getHanzi(stu.getFeature());
                                        if (!flag) {
                                            try {
                                                byte[] bytes = StringUtil.hexDecode(stu.getFeature());
                                                String ObjContent = new String(bytes, "UTF-8");
                                                stu.setFeature(ObjContent);
                                            } catch (Exception e) {
                                                e.printStackTrace();
                                            }
                                        }
                                    }
                                }
                            }
                            result.setDefaultModel("stuList", stuList);
                        }
                    }
                }

                TgTracking track = new TgTracking();
                track.setClient(clkeyname);
                List<TgTracking> traList = trackingDao.findByExample(track);
                if (traList != null && traList.size() > 0) {
                    TgState state = new TgState();
                    for (TgTracking tra : traList) {
                        // 状态
                        if (tra.getState() != null
                                && !"".equals(tra.getState())) {
                            if (tra.getState().contains(",")) {
                                String[] stat = tra.getState().split(",");
                                if (stat.getClass().isArray()) {
                                    String stats = "";
                                    for (int i = 0; i < stat.length; i++) {
                                        state.setKeyname(stat[i]);
                                        List<TgState> stateList = stateDao
                                                .findByExample(state);
                                        if (stateList != null
                                                && stateList.size() > 0) {
                                            stats = stats
                                                    + stateList.get(0)
                                                    .getName() + ",";
                                        }
                                    }
                                    String[] sta = stats.split(",");
                                    List<State> staList = new ArrayList<State>();
                                    List<String> person = new ArrayList<>(
                                            Arrays.asList(sta));
                                    for (int j = 0; j < person.size(); j++) {
                                        State states = new State();
                                        states.setState(person.get(j));
                                        staList.add(states);
                                    }
                                    tra.setSlist(staList);
                                }
                            } else {
                                state.setKeyname(tra.getState());
                                List<TgState> stateList = stateDao
                                        .findByExample(state);
                                if (stateList != null && stateList.size() > 0) {
                                    tra.setState(stateList.get(0).getName());
                                }
                            }
                        }
                        //时间
                        if (tra.getRemind_date() != null && !"".equals(tra.getRemind_date())) {
                            String createTime = sdf1.format(new Date(tra.getRemind_date() * 1000));
                            tra.setStartTime(createTime);
                        }
                        // 备注内容
                        if (tra.getRemark() != null
                                && !"".equals(tra.getRemark())) {
                            boolean flag = StringUtil.getHanzi(tra.getRemark());
                            if (!flag) {
                                try {
                                    byte[] bytes = StringUtil.hexDecode(tra
                                            .getRemark());
                                    String ObjContent = new String(bytes,
                                            "UTF-8");
                                    tra.setRemark(ObjContent);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                        }

                        // 负责人
                        TgUserinfo user = new TgUserinfo();
                        user.setUsername(tra.getUsername());
                        List<TgUserinfo> ulist = userinfoDao
                                .findByExample(user);
                        if (ulist != null && ulist.size() > 0) {
                            tra.setNickname(ulist.get(0).getNickname());
                        }
                        // 时间转换
                        if (tra.getCdate() != null
                                && !"".equals(tra.getCdate())) {
                            String createTime = sdf2.format(new Date(tra
                                    .getCdate() * 1000));
                            tra.setCreateTime(createTime);
                        }

                    }
                }


                TgUserinfo userinfo = new TgUserinfo();
                userinfo.setJob("课程顾问");
                List<TgUserinfo> uList = userinfoDao
                        .getUserInfoByUserInfo(userinfo);


                result.setDefaultModel("reserve", reserve);
                result.setDefaultModel("client", client);
                result.setDefaultModel("res", res);
                result.setDefaultModel("uList", uList);
                result.setDefaultModel("traList", traList);
                result.setDefaultModel("keyname", keyname);
                return result;
            }
        });
        return new ModelAndView("system/system_reserve_view", modelMap);
    }

    //预约详情-添加信息


    //咨询师业务管理--客户接待数据管理
    @RequestMapping(value = "/system_reception_list")
    public ModelAndView system_reception_list(ModelMap modelMap, final BaseVo vo,
                                              final HttpServletRequest request, final HttpServletResponse response)
            throws Exception {
        modelMap = WebExecutor.execute(logger, vo, new Biz() {
            public Result process() {
                Result result = new ResultSupport(true);
                String knickname = request.getParameter("knickname");
                String snickname = request.getParameter("snickname");
                String rkey = request.getParameter("rkey");
                String worth = request.getParameter("worth");
                String phone = request.getParameter("phone");
                String email = request.getParameter("email");
                String qq = request.getParameter("qq");
                String source = request.getParameter("source");
                String stnickname = request.getParameter("stnickname");
                String time = request.getParameter("time");

                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

                TgReception reception = new TgReception();
                TgUser user = UserUtil.getUserFromCookies();
                if (user == null) {
                    return result;
                } else if (user.getUsergroup() == 3) {
                    reception.setUsername(user.getUsername());
                }

                if (knickname != null && !"".equals(knickname)) {
                    reception.setKnickname(knickname);
                }
                if (snickname != null && !"".equals(snickname)) {
                    reception.setSnickname(snickname);
                }
                if (stnickname != null && !"".equals(stnickname)) {
                    reception.setStnickname(stnickname);
                }
                if (rkey != null && !"".equals(rkey)) {
                    if (rkey.equals("1")) {
                        reception.setRkey1(rkey);
                    } else if (rkey.equals("2")) {
                        reception.setRkey2(rkey);
                    }
                    reception.setRkey(rkey);
                }
                if (source != null && !"".equals(source)) {
                    reception.setSource(source);
                }

                if (worth != null && !"".equals(worth)) {
                    reception.setWorth(Integer.parseInt(worth));
                }
                if (phone != null && !"".equals(phone)) {
                    reception.setPhone(phone);
                }
                if (email != null && !"".equals(email)) {
                    reception.setEmail(email);
                }
                if (qq != null && !"".equals(qq)) {
                    reception.setQq(qq);
                }
                if (time != null && !"".equals(time)) {
                    reception.setTime(time);
                }
                Integer currPage = 1;
                if (vo.getCurrPage() != null && !"".equals(vo.getCurrPage())) {
                    currPage = vo.getCurrPage();
                }
                Integer total = receptionDao.getReceptionCount(reception);
                Page page = PageUtil.createPage(8, currPage, total);
                List<TgReception> list = receptionDao.getReceptionByType(reception, page);
                Gson gson = new Gson();
                if (list != null && list.size() > 0) {
                    TgTracking tracking = new TgTracking();
                    for (TgReception rece : list) {
                        //跟踪条数
                        tracking.setClient(rece.getClient());
                        List<TgTracking> listsize = trackingDao.findByExample(tracking);
                        rece.setTracksize(listsize.size() + "");

                        //日期转换
                        if (rece.getDate() != null && !"".equals(rece.getDate())) {
                            String gtime = sdf.format(new Date(rece.getDate() * 1000));
                            rece.setGtime(gtime);
                        }
                        //联系方式
                        if (rece.getPhone() != null && !"".equals(rece.getPhone())) {
                            if (rece.getPhone().contains("[{")) {
                                List<Phone> phone1 = gson.fromJson(rece.getPhone(),
                                        new TypeToken<List<Phone>>() {
                                        }.getType());
                                rece.setPhlist(phone1);
                            }
                        }

                        //学生信息
                        TgClient client = new TgClient();
                        client.setKeyname(rece.getClient());
                        List<TgStudent> stuList = null;

                        List<TgClient> cliList = clientDao.findByExample(client);
                        if (cliList != null && cliList.size() > 0) {
                            TgStudent stu1 = new TgStudent();
                            stu1.setPkey(cliList.get(0).getKeyname());
                            stuList = studentDao.findByExample(stu1);

                            String student = rece.getStudent();
                            if (student != null && !"".equals(student)) {
                                try {
                                    JsonValidator json = new JsonValidator();
                                    Boolean flag = json.validate(student);
                                    String ObjContent = "";
                                    if (flag) {
                                        ObjContent = student;
                                    } else {
                                        byte[] bytes = StringUtil.hexDecode(student);
                                        ObjContent = new String(bytes, "UTF-8");
                                    }
                                    if (ObjContent.contains("key")) {
                                        JSONObject obj = new JSONObject(ObjContent);
                                        List<StuMsg> smlist = new ArrayList<StuMsg>();
                                        if (stuList != null && stuList.size() > 0) {
                                            for (TgStudent s : stuList) {
                                                JSONObject obj2 = null;
                                                if (ObjContent.contains("\"key\":\"" + s.getKeyname() + "\"")) {
                                                    obj2 = obj.getJSONObject(s.getKeyname());
                                                }
                                                if (obj2 != null) {
                                                    StuMsg stuMsg = new StuMsg();
                                                    stuMsg.setKeyname(obj2.getString("key"));
                                                    stuMsg.setMoneylog(obj2.getString("moneylog"));
                                                    stuMsg.setPrice(obj2.getString("price"));
                                                    stuMsg.setReason(obj2.getString("reason"));
                                                    stuMsg.setResult(obj2.getString("result"));
                                                    stuMsg.setTestuser(s.getNickname());
                                                    smlist.add(stuMsg);
                                                }
                                                rece.setSmlist(smlist);
                                            }
                                        }
                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                    }
                }

                result.setDefaultModel("reception", reception);
                result.setDefaultModel("list", list);
                result.setDefaultModel("page", page);
                result.setDefaultModel("knickname", knickname);
                result.setDefaultModel("snickname", snickname);
                result.setDefaultModel("rkey", rkey);
                result.setDefaultModel("worth", worth);
                result.setDefaultModel("phone", phone);
                result.setDefaultModel("email", email);
                result.setDefaultModel("qq", qq);
                result.setDefaultModel("source", source);
                result.setDefaultModel("stnickname", stnickname);
                result.setDefaultModel("time", time);

                return result;
            }
        });
        return new ModelAndView("system/system_reception_list", modelMap);
    }

    //删除接待数据
    @RequestMapping(value = "/system_reception_del")
    public ModelAndView system_reception_del(ModelMap modelMap, final BaseVo vo,
                                             final HttpServletRequest request, HttpServletResponse response)
            throws BaseException {
        modelMap = JsonExecutor.execute(logger, vo, new JsonBiz() {
            public Result process() {
                Result result = new ResultSupport(true);

                String keyname = request.getParameter("key");
                TgUser user = UserUtil.getUserFromCookies();
                if (user != null) {
                    if (keyname != null && !"".equals(keyname)) {
                        TgReception reception = new TgReception();
                        reception.setKeyname(keyname);
                        List<TgReception> list = receptionDao.findByExample(reception);
                        if (list != null && list.size() > 0) {
                            receptionDao.delete(TgReception.class, list.get(0).getId());
                        }
                    }
                }
                return result;
            }
        });

        return new ModelAndView("", modelMap);
    }


    //咨询师业务管理--接待详情
    @RequestMapping(value = "/system_reception_view")
    public ModelAndView system_reception_view(ModelMap modelMap, final BaseVo vo,
                                              final HttpServletRequest request, final HttpServletResponse response)
            throws Exception {
        modelMap = WebExecutor.execute(logger, vo, new Biz() {
            public Result process() {
                Result result = new ResultSupport(true);
                String keyname = request.getParameter("keyname");
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                TgReception res = new TgReception();
                res.setKeyname(keyname);
                List<TgStudent> stuList = null;
                List<TgReception> reslist = receptionDao.getReceptionByKeyname(res);
                Gson gson = new Gson();
                if (reslist != null && reslist.size() > 0) {
                    res = reslist.get(0);
                    TgOffice office = new TgOffice();
                    office.setKeyname(res.getRegion());
                    List<TgOffice> list = tgOfficeDao.findByExample(office);
                    if (list != null && list.size() > 0) {
                        office = list.get(0);
                        TgMethod method = new TgMethod();
                        method.setCenter_id(office.getId());
                        List<TgMethod> mList = methodDao.findByExample(method);
                        result.setDefaultModel("mList", mList);
                    }
                    for (TgReception stu : reslist) {
                        if (stu.getFeature() != null && !"".equals(stu.getFeature())) {
                            boolean flag = StringUtil.getHanzi(stu.getFeature());
                            if (!flag) {
                                try {
                                    byte[] bytes = StringUtil.hexDecode(stu.getFeature());
                                    String ObjContent = new String(bytes, "UTF-8");
                                    stu.setFeature(ObjContent);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                        if (stu.getPhone() != null && !"".equals(stu.getPhone())) {
                            if (stu.getPhone().contains("[{")) {
                                List<Phone> phone = gson.fromJson(stu.getPhone(),
                                        new TypeToken<List<Phone>>() {
                                        }.getType());
                                stu.setPhlist(phone);
                            }
                        }
                        if (stu.getDate() != null && !"".equals(stu.getDate())) {
                            String gtime = sdf.format(new Date(stu.getDate() * 1000));
                            stu.setGtime(gtime);
                        }
                        if (stu.getRep_date() != null && !"".equals(stu.getRep_date())) {
                            String req_time = sdf.format(new Date(stu.getRep_date() * 1000));
                            stu.setRep_time(req_time);
                        }
                        if (stu.getRep_date1() != null && !"".equals(stu.getRep_date1())) {
                            String req_time1 = sdf.format(new Date(stu.getRep_date1() * 1000));
                            stu.setRep_time1(req_time1);
                        }
                        if (stu.getEarnest_date() != null && !"".equals(stu.getEarnest_date())) {
                            String ear_time = sdf.format(stu.getEarnest_date() * 1000);
                            stu.setEar_time(ear_time);
                        }
                        //学生信息
                        TgClient client = new TgClient();
                        client.setKeyname(stu.getClient());
                        List<TgClient> cliList = clientDao.findByExample(client);
                        if (cliList != null && cliList.size() > 0) {
                            TgStudent stu1 = new TgStudent();
                            stu1.setPkey(cliList.get(0).getKeyname());
                            stuList = studentDao.findByExample(stu1);

                            String student = stu.getStudent();
                            if (student != null && !"".equals(student)) {
                                try {
                                    JsonValidator json = new JsonValidator();
                                    Boolean flag = json.validate(student);
                                    String ObjContent = "";
                                    if (flag) {
                                        ObjContent = student;
                                    } else {
                                        byte[] bytes = StringUtil.hexDecode(student);
                                        ObjContent = new String(bytes, "UTF-8");
                                    }
                                    if (ObjContent.contains("key")) {
                                        JSONObject obj = new JSONObject(ObjContent);

                                        if (stuList != null && stuList.size() > 0) {
                                            for (TgStudent s : stuList) {
                                                List<StuMsg> smlist = new ArrayList<StuMsg>();
                                                JSONObject obj2 = null;
                                                if (ObjContent.contains("\"key\":\"" + s.getKeyname() + "\"")) {
                                                    obj2 = obj.getJSONObject(s.getKeyname());
                                                }
                                                if (obj2 != null) {
                                                    StuMsg stuMsg = new StuMsg();
                                                    stuMsg.setKeyname(obj2.getString("key"));
                                                    stuMsg.setMoneylog(obj2.getString("moneylog"));
                                                    stuMsg.setPrice(obj2.getString("price"));
                                                    stuMsg.setReason(obj2.getString("reason"));
                                                    stuMsg.setRemark(obj2.getString("remark"));
                                                    stuMsg.setResult(obj2.getString("result"));
                                                    stuMsg.setTestuser(obj2.getString("testuser"));
                                                    smlist.add(stuMsg);
                                                    s.setSmlist(smlist);
                                                    s.setTestuser(obj2.getString("testuser"));
                                                }
                                            }
                                        }
                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                    }
                }


                TgUserinfo user1 = new TgUserinfo();
                user1.setJob("课程顾问");
                List<TgUserinfo> uList = userinfoDao.getUserInfoByUserInfo(user1);
                List<TgOffice> offList = tgOfficeDao.findAll(TgOffice.class);

                result.setDefaultModel("uList", uList);
                result.setDefaultModel("offList", offList);
                result.setDefaultModel("res", res);
                result.setDefaultModel("key", keyname);
                result.setDefaultModel("stuList", stuList);
                return result;
            }
        });
        return new ModelAndView("system/system_reception_view", modelMap);
    }
    //区域销售主管审核体验课
    @RequestMapping(value = "/update_tiyanke")
    public ModelAndView update_tiyanke(ModelMap modelMap, final BaseVo vo,
                                            final HttpServletRequest request, final HttpServletResponse response)
            throws Exception {
        modelMap = WebExecutor.execute(logger, vo, new Biz() {
            public Result process() {
            	Result result = new ResultSupport(true);
    			String id = request.getParameter("id");
    			Tiyanke findById = tgTiyankeDao.findById(Tiyanke.class, Long.valueOf(id));
    			Long stu_id = findById.getStu_id();
    			String stu_name = findById.getStu_name();
    	//		Long tea_id = findById.getTea_id();
    			String tea_name = findById.getTea_name();
    			String center = findById.getCenter();
					try {
						stu_name = URLEncoder.encode(stu_name, "utf-8");
						center = URLEncoder.encode(center, "utf-8");
						tea_name = URLEncoder.encode(tea_name, "utf-8");
					} catch (UnsupportedEncodingException e) {
						e.printStackTrace();
					}
				String url = "http://www.yueqiao.org/web/teaweb/add_experienceClass.json?stu_id="+stu_id+"&stu_name="+stu_name+"&center="+center+"&tea_name="+tea_name;
				String objStr = HttpUtil.doGet(url, "", "utf-8", true);
				net.sf.json.JSONObject obj =  net.sf.json.JSONObject.fromObject(objStr);
				String msg = obj.getString("msg");
				
				if(msg.equals("1")){
					Tiyanke tiyanke = new Tiyanke();
					tiyanke.setId(Long.valueOf(id));
					tiyanke.setShenhe(1);
					tgTiyankeDao.update(tiyanke);
				}
				
   				Tiyanke tiyanke = new Tiyanke();
   				tiyanke.setCenter(findById.getCenter());
				Integer currPage = vo.getCurrPage() == null ? 1 : vo.getCurrPage();
				Integer totalt = tgTiyankeDao.getCountByCenter(tiyanke);
			    Page page1 = PageUtil.createPage(10, currPage, totalt);
				List<Tiyanke> list1 = tgTiyankeDao.findTiyankeList(tiyanke,page1);
				List<TgOffice> office_List = tgOfficeDao.findAll(TgOffice.class);//查询中心
			    result.setDefaultModel("office_List", office_List);
				result.setDefaultModel("list", list1);
				result.setDefaultModel("page", page1);
    			return result;
            }
        });
        return new ModelAndView("work/tiyanke", modelMap);
    }

    //向区域销售主管申请给高意向的学员上一次体验课
	@RequestMapping(value = "/experienceClass")
	public ModelAndView experienceClass(ModelMap modelMap, final BaseVo vo,
			final HttpServletRequest request, final HttpServletResponse response)
					throws Exception {
		modelMap = JsonExecutor.execute(logger, vo, new JsonBiz() {
			public Result process() {
				Result result = new ResultSupport(true);
				String keyname = request.getParameter("keyname");
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				TgUser user=UserUtil.getUserFromCookies();
				TgReception res = new TgReception();
				res.setKeyname(keyname);
				String stu_id="";
                String stu_name="";
                Tiyanke tiyan = new Tiyanke();
				List<TgReception> reslist = receptionDao.getReceptionByKeyname(res);
				if (reslist != null && reslist.size() > 0) {
					res = reslist.get(0);
					//学生信息
                    TgClient client = new TgClient();
                    client.setKeyname(res.getClient());
                    List<TgClient> cliList = clientDao.findByExample(client);
                    if (cliList != null && cliList.size() > 0) {
						TgStudent stu1 = new TgStudent();
                        stu1.setPkey(cliList.get(0).getKeyname());
                        List<TgStudent> stuList = studentDao.findByExample(stu1);
                        stu_id=String.valueOf(stuList.get(0).getId());
                        stu_name=stuList.get(0).getNickname();
                    }
                    tiyan.setStu_id(Long.valueOf(stu_id));
                    tiyan.setStu_name(stu_name);
                    if(tgTiyankeDao.countEqual(tiyan)>0){
                    	result.setDefaultModel("msg", "2");
                    }else{
                    	String center=user.getRegions();
    					String tea_name=user.getNickname();
    					int tea_id=user.getId();
    					try {
    						tiyan.setTea_id(Long.valueOf(tea_id));
    						tiyan.setTea_name(tea_name);
    						tiyan.setCenter(center);
    						tiyan.setCreate_time(sdf.parse(sdf.format(new Date())));
    						tgTiyankeDao.insert(tiyan);
    						result.setDefaultModel("msg", "1");
    					} catch (ParseException e) {
    						e.printStackTrace();
    					}
                    }
				}else {
					result.setDefaultModel("msg", "0");
				}
				return result;
			}
		});
		return new ModelAndView("", modelMap);
	}

    //根据地区显示老师
    @RequestMapping(value = "/system_city")
    public ModelAndView system_city(ModelMap modelMap, final BaseVo vo,
                                    final HttpServletRequest request, HttpServletResponse response)
            throws BaseException {
        modelMap = JsonExecutor.execute(logger, vo, new JsonBiz() {
            public Result process() {
                Result result = new ResultSupport(true);
                String region = request.getParameter("city");

                TgUserinfo use1 = new TgUserinfo();
                use1.setJob("训练导师");
                if (region != null && !"".equals(region)) {
                    use1.setRegion(region);
                }

                TgUserinfo user = new TgUserinfo();
                user.setJob("课程顾问");
                if (region != null && !"".equals(region)) {
                    user.setRegion(region);
                }

                TgUserinfo user_info1 = new TgUserinfo();
                user_info1.setJob("在线课程顾问");
                if (region != null && !"".equals(region)) {
                    user_info1.setRegion(region);
                }

                List<TgUserinfo> uList = userinfoDao.getUserInfoByUserInfo(user);
                List<TgUserinfo> use1List = userinfoDao.getUserInfoByUserInfo(use1);
                List<TgUserinfo> uses1List = userinfoDao.getUserInfoByUserInfo(user_info1);
                List<TgOffice> list = tgOfficeDao.findAll(TgOffice.class);

                result.setDefaultModel("use1List", use1List);
                result.setDefaultModel("uses1List", uses1List);
                result.setDefaultModel("uList", uList);
                result.setDefaultModel("list", list);
                return result;
            }
        });

        return new ModelAndView("", modelMap);
    }

    //咨询师业务管理--进入客户资源分配页面
    @RequestMapping(value = "/system_client_allot")
    public ModelAndView system_client_allot(ModelMap modelMap, final BaseVo vo,
                                            final HttpServletRequest request, final HttpServletResponse response)
            throws Exception {
        modelMap = WebExecutor.execute(logger, vo, new Biz() {
            public Result process() {
                Result result = new ResultSupport(true);
                String type = request.getParameter("type");

                TgUserinfo user = new TgUserinfo();
                user.setJob("课程顾问");
                List<TgUserinfo> uList = userinfoDao.getUserInfoByUserInfo(user);


                TgUserinfo user1 = new TgUserinfo();
                user1.setJob("在线课程顾问");
                List<TgUserinfo> uList1 = userinfoDao.getUserInfoByUserInfo(user1);

                List<TgSource> souList = sourceDao.findAll(TgSource.class);
                List<TgOffice> list = tgOfficeDao.findAll(TgOffice.class);

                result.setDefaultModel("type", type);
                result.setDefaultModel("uList", uList);
                result.setDefaultModel("uList1", uList1);
                result.setDefaultModel("list", list);
                result.setDefaultModel("souList", souList);
                return result;
            }
        });
        return new ModelAndView("system/system_client_allot", modelMap);
    }

    //咨询师业务管理--异步获取客户资源
    @RequestMapping(value = "/get_client_allot")
    public ModelAndView get_client_allot(ModelMap modelMap, final BaseVo vo,
                                         final HttpServletRequest request, HttpServletResponse response)
            throws BaseException {
        modelMap = JsonExecutor.execute(logger, vo, new JsonBiz() {
            public Result process() {
                Result result = new ResultSupport(true);
                String source = request.getParameter("source");
                String category = request.getParameter("category");
                String province = request.getParameter("province");
                String city = request.getParameter("city");
                String address = request.getParameter("address");
                String nickname = request.getParameter("nickname");
                String state = request.getParameter("state");
                String intention = request.getParameter("intention");

                String phone = request.getParameter("phone");
                String email = request.getParameter("email");
                String qq = request.getParameter("qq");
                String type = request.getParameter("type");

                TgUser user = UserUtil.getUserFromCookies();
                TgClient client = new TgClient();

                if (user.getUsergroup() == 3) {
                    if (user.getMenu() != null) {
                        if (!user.getMenu().contains("e") || type.equals("2")) {
                            client.setUsername(user.getUsername());
                        }
                    } else {
                        client.setUsername(user.getUsername());
                    }

                }
                if (source != null && !"".equals(source)) {
                    client.setSource(source);
                }
                if (category != null && !"".equals(category)) {
                    client.setCategory(category);
                }
                if (province != null && !"".equals(province)) {
                    client.setProvince(province);
                }
                if (city != null && !"".equals(city)) {
                    client.setCity(city);
                }
                if (address != null && !"".equals(address)) {
                    client.setAddress(address);
                }
                if (nickname != null && !"".equals(nickname)) {
                    client.setNickname(nickname);
                }
                if (intention != null && !"".equals(intention)) {
                    client.setIntention(intention);
                }
                if (phone != null && !"".equals(phone)) {
                    client.setPhone(phone);
                }
                if (email != null && !"".equals(email)) {
                    client.setEmail(email);
                }
                if (qq != null && !"".equals(qq)) {
                    client.setQq(qq);
                }
                //判断客户状态
                if (state != null && !"".equals(state)) {
                    if (state.equals("已预约")) {
                        client.setRenum(2);
                        client.setRemin(1);
                    } else if (state.equals("未出现")) {
                        client.setRenum(3);
                        client.setRemin(3);
                    } else if (state.equals("已缴费")) {
                        client.setRecenum(6);
                        client.setRecemin(6);
                    } else if (state.equals("已测评")) {
                        client.setRecenum(5);
                        client.setRecemin(1);
                    }else if (state.equals("无")) {
                	client.setRenum_n(0);
                    }
                }

                List<TgClient> list = clientDao.getClientByTypes(client);

                result.setDefaultModel("list", list);
                return result;
            }
        });

        return new ModelAndView("", modelMap);
    }

    //咨询师业务管理--客户资源转接
    @RequestMapping(value = "/system_client_allot_go")
    public ModelAndView system_client_allot_go(ModelMap modelMap, final BaseVo vo,
                                               final HttpServletRequest request, HttpServletResponse response)
            throws BaseException {
        modelMap = JsonExecutor.execute(logger, vo, new JsonBiz() {
            public Result process() {
                Result result = new ResultSupport(true);
                String clients = request.getParameter("clients");
                String lodusername = request.getParameter("target");
                if (clients != null && !"".equals(clients)) {
                    String[] ids = clients.split(",");
                    if (ids != null && ids.length > 0) {
                        for (int i = 0; i < ids.length; i++) {
                            TgClient client = new TgClient();
                            client = clientDao.findById(TgClient.class, Long.valueOf(ids[i]));
                            if (client != null && !"".equals(client)) {
                                client.setLodusername(lodusername);
                                client.setUsername("");
                                if (client.getRawusername() == null && client.getRawusername().equals("")) {
                                    client.setRawusername(client.getUsername());
                                }

                                if (client.getType() != null && !"".equals(client.getType())) {//1代表网站表，2代表问卷表，3代表汇总表
	                                    JsVote vote = new JsVote();
	                                    vote = voteDao.findById(JsVote.class, client.getFrom_id());
	                                    if(vote==null||"".equals(vote)||"null".equals(vote)){
	                                    	JsFromUser fromuser = new JsFromUser();
											fromuser = fromuserDao.findById(JsFromUser.class, client.getFrom_id());
											if(fromuser==null||"".equals(fromuser)||"null".equals(fromuser)){
												TgClientImp clientImp = new TgClientImp();
												clientImp = clientImpDao.findById(TgClientImp.class, client.getFrom_id());
												if(clientImp!=null || "".equals(clientImp)||"null".equals(clientImp)){
													clientImp.setTo_username(lodusername);
													clientImpDao.update(clientImp);
												}else{
													client.setUsername(lodusername);
												}
											}else{
											fromuser.setUsername(lodusername);
											fromuserDao.update(fromuser);
											}
	                                    }else{
	                                    vote.setUsername(lodusername);
	                                    voteDao.update(vote);
	                                    }
                                }
                                clientDao.update(client);
                            }

                        }
                    }
                }
                return result;
            }
        });

        return new ModelAndView("", modelMap);
    }

    //咨询师业务管理--咨询师临时权限管理
    @RequestMapping(value = "/reserve_temp_permiss")
    public ModelAndView reserve_temp_permiss(ModelMap modelMap, final BaseVo vo,
                                             HttpServletRequest request, final HttpServletResponse response)
            throws Exception {
        modelMap = WebExecutor.execute(logger, vo, new Biz() {
            public Result process() {
                Result result = new ResultSupport(true);
                List<TgOffice> offlist = tgOfficeDao.findAll(TgOffice.class);
                TgUserinfo user = new TgUserinfo();
                user.setJob("课程顾问");
                List<TgUserinfo> uList = userinfoDao.getUserInfoByUserInfo(user);

                result.setDefaultModel("offlist", offlist);
                result.setDefaultModel("uList", uList);
                return result;
            }
        });
        return new ModelAndView("system/reserve_temp_permiss", modelMap);
    }

    //异步获取临时权限
    @RequestMapping(value = "/reserve_temp_permiss_search")
    public ModelAndView reserve_temp_permiss_search(ModelMap modelMap, final BaseVo vo,
                                                    final HttpServletRequest request, HttpServletResponse response)
            throws BaseException {
        modelMap = JsonExecutor.execute(logger, vo, new JsonBiz() {
            public Result process() {
                Result result = new ResultSupport(true);
                String username = request.getParameter("username");
                TgUserinfo info = new TgUserinfo();
                info.setUsername(username);
                List<TgUserinfo> list = userinfoDao.findByExample(info);
                if (list != null && list.size() > 0) {
                    String region_temp = list.get(0).getRegion_temp();
                    result.setDefaultModel("region_temp", region_temp);
                }
                return result;
            }
        });
        return new ModelAndView("", modelMap);
    }

    //异步添加临时权限
    @RequestMapping(value = "/reserve_temp_permiss_go")
    public ModelAndView reserve_temp_permiss_go(ModelMap modelMap, final BaseVo vo,
                                                final HttpServletRequest request, HttpServletResponse response)
            throws BaseException {
        modelMap = JsonExecutor.execute(logger, vo, new JsonBiz() {
            public Result process() {
                Result result = new ResultSupport(true);
                String username = request.getParameter("target");
                String regions = request.getParameter("regions");
                TgUserinfo info = new TgUserinfo();
                info.setUsername(username);
                List<TgUserinfo> list = userinfoDao.findByExample(info);
                if (list != null && list.size() > 0) {
                    info = list.get(0);
                    if (info != null) {
                        info.setRegion_temp(regions);
                        userinfoDao.update(info);
                    }
                }
                return result;
            }
        });
        return new ModelAndView("", modelMap);
    }

    //咨询师业务管理--无效客户资源管理
    @RequestMapping(value = "/system_client_temp")
    public ModelAndView system_client_temp(ModelMap modelMap, final BaseVo vo,
                                           final HttpServletRequest request, final HttpServletResponse response)
            throws Exception {
        modelMap = WebExecutor.execute(logger, vo, new Biz() {
            public Result process() {
                Result result = new ResultSupport(true);
                String nickname = request.getParameter("nickname");
                String startTime = request.getParameter("startTime");
                String endTime = request.getParameter("endTime");
                String intention = request.getParameter("intention");
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                TgClient client = new TgClient();
                client.setInvalid(1);
                if (nickname != null && !"".equals(nickname)
                        && !"null".equals(nickname)) {
                    client.setNickname(nickname);
                    result.setDefaultModel("nickname", nickname);
                }

                if (startTime != null && !"".equals(startTime)
                        && !"null".equals(startTime)) {

                    try {
                        Date date = sdf.parse(startTime);
                        client.setStartTime(date.getTime() / 1000);
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                }
                if (endTime != null && !"".equals(endTime)
                        && !"null".equals(endTime)) {
                    try {
                        Date date = sdf.parse(endTime);
                        client.setStartTime(date.getTime() / 1000);
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                }

                if (intention != null && !"".equals(intention)
                        && !"null".equals(intention)) {
                    client.setIntention(intention);
                    result.setDefaultModel("intention", intention);
                }

                Integer currPage = 1;
                if (vo.getCurrPage() != null && !"".equals(vo.getCurrPage())) {
                    currPage = vo.getCurrPage();
                }

                Integer total = clientDao.getClientCount(client);
                Page page = PageUtil.createPage(15, currPage, total);
                List<TgClient> list = clientDao.getClientByTypeCdate(client, page);

                if (list != null && list.size() > 0) {
                    TgStudent student = new TgStudent();
                    for (TgClient c : list) {
                        // 时间和备注内容
                        try {
                            if (c.getMdate() != null
                                    && !"".equals(c.getMdate())) {

                                String date = sdf2.format(new Date(
                                        c.getMdate() * 1000));
                                c.setModeTime(date);
                            }

                            if (c.getCdate() != null
                                    && !"".equals(c.getCdate())) {
                                String date = sdf2.format(new Date(
                                        c.getCdate() * 1000));
                                c.setDateTime(date);
                            }

                            if (c.getDescs() != null
                                    && !"".equals(c.getDescs())) {
                                boolean flag = StringUtil.getHanzi(c.getDescs());
                                if (!flag) {
                                    try {
                                        byte[] bytes = StringUtil.hexDecode(c
                                                .getDescs());
                                        String ObjContent = new String(bytes,
                                                "UTF-8");
                                        c.setDescs(ObjContent);
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                }
                            }

                            if (c.getPhone() != null && !"".equals(c.getPhone())) {
                                Gson gson = new Gson();// new一个Gson对象
                                if (c.getPhone().contains("[{")) {
                                    List<Phone> phone = gson.fromJson(c.getPhone(),
                                            new TypeToken<List<Phone>>() {
                                            }.getType());
                                    c.setPhlist(phone);
//								c.setPhone(c.getPhlist().get(0).getPhone());
                                }
                            }
                            // 学生
                            if (c.getKeyname() != null
                                    && !"".equals(c.getKeyname())) {
                                student.setPkey(c.getKeyname());
                                List<TgStudent> studentList = studentDao
                                        .findByExample(student);
                                if (studentList != null && studentList.size() > 0) {
                                    String stu = "";
                                    String context = "";

                                    for (int i = 0; i < studentList.size(); i++) {
                                        String age = studentList.get(i).getAge();
                                        if (age == null) {
                                            age = "0";
                                        }
                                        stu += studentList.get(i).getNickname()
                                                + "<span class=\"caption\">("
                                                + age + "岁"
                                                + ")</span>,";

                                        String con = "";
                                        String Contentq = "";
                                        if (studentList.get(i).getFeature() != null && !"".equals(studentList.get(i).getFeature())) {
                                            boolean flag1 = StringUtil.getHanzi(studentList.get(i).getFeature());
                                            if (!flag1) {
                                                byte[] bytes = StringUtil.hexDecode(con);
                                                try {
                                                    Contentq += new String(bytes, "UTF-8");
                                                } catch (UnsupportedEncodingException e) {
                                                    e.printStackTrace();
                                                }
                                                if (Contentq != null && !"".equals(Contentq)) {
                                                    con = studentList.get(i).getNickname() + ":(" + Contentq + ")";
                                                }
                                            } else {
                                                if (studentList.get(i).getFeature() != null && !"".equals(studentList.get(i).getFeature())) {
                                                    con = studentList.get(i).getNickname() + ":(" + studentList.get(i).getFeature() + ")";
                                                }
                                            }
                                            if (con != null && !"".equals(con)) {
                                                context = context + con + "</br>";
                                                if (context.contains("\"")) {
                                                    context = context.replace('"', ' ');
                                                }
                                            }
                                        }
                                        c.setFeature(context);
                                    }
                                    c.setStudent(stu);
                                }
                            }
                            // 最后更新信息和状态和总更新数量
                            if (c.getLastdate() != null && !"".equals(c.getLastdate())) {
                                String createTime = sdf.format(new Date(c.getLastdate() * 1000));
                                c.setNewTime(createTime);
                            }
                            if (c.getLast_track() != null && !"".equals(c.getLast_track())) {
                                c.setLast_track(c.getLast_track().replace("&nbsp;", "").trim());
                                if (StringUtil.isNum(c.getLast_track())) {
                                    c.setFallow(c.getLast_track());
                                } else {
                                    boolean flag = StringUtil.getHanzi(c.getLast_track());
                                    if (!flag) {
                                        byte[] bytes = StringUtil.hexDecode(c.getLast_track());
                                        String ObjContent = new String(bytes, "UTF-8");
                                        c.setFallow(ObjContent);
                                    } else {
                                        c.setFallow(c.getLast_track());
                                    }
                                }
                            }
                            if (c.getTrackings() != null && !"".equals(c.getTrackings())) {
                                c.setTracksize(String.valueOf(c.getTrackings()));
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }

                TgUserinfo userinfo = new TgUserinfo();
                userinfo.setJob("课程顾问");
                List<TgUserinfo> uList = userinfoDao
                        .getUserInfoByUserInfo(userinfo);

                List<TgState> stateList = stateDao.findAll(TgState.class);

                result.setDefaultModel("stateList", stateList);
                result.setDefaultModel("startTime", startTime);
                result.setDefaultModel("endTime", endTime);
                result.setDefaultModel("page", page);
                result.setDefaultModel("list", list);
                result.setDefaultModel("uList", uList);

                return result;
            }
        });
        return new ModelAndView("system/system_client_temp", modelMap);
    }

    //删除无效客户
    @RequestMapping(value = "/system_client_del")
    public ModelAndView system_client_del(ModelMap modelMap, final BaseVo vo,
                                          final HttpServletRequest request, HttpServletResponse response)
            throws BaseException {
        modelMap = JsonExecutor.execute(logger, vo, new JsonBiz() {
            public Result process() {
                Result result = new ResultSupport(true);
                String keyname = request.getParameter("key");
                String id = request.getParameter("clients");
                TgUser user = UserUtil.getUserFromCookies();
                if (user != null) {
                    if (keyname != null && !"".equals(keyname)) {
                        TgClient client = new TgClient();
                        client.setKeyname(keyname);
                        List<TgClient> list = clientDao.findByExample(client);
                        if (list != null && list.size() > 0) {
                            clientDao.delete(TgClient.class, list.get(0).getId());

                        }
                    }
                }

                if (id != null && !"".equals(id)) {
                    if (id.contains(",")) {
                        String[] ids = id.split(",");
                        for (int i = 0; i < ids.length; i++) {
                            clientDao.delete(TgClient.class, (long) Integer.parseInt(ids[i]));
                        }
                    } else {
                        clientDao.delete(TgClient.class, (long) Integer.parseInt(id));
                    }
                }
                return result;
            }
        });

        return new ModelAndView("", modelMap);
    }

    //咨询师业务管理--过期预约查询
    @RequestMapping(value = "/system_reserve_expired")
    public ModelAndView system_reserve_expired(ModelMap modelMap, final BaseVo vo,
                                               final HttpServletRequest request, final HttpServletResponse response)
            throws Exception {
        modelMap = WebExecutor.execute(logger, vo, new Biz() {
            @SuppressWarnings("deprecation")
            public Result process() {
                Result result = new ResultSupport(true);
                String nickname = request.getParameter("nickname");
                String startTime = request.getParameter("startTime");
                String endTime = request.getParameter("endTime");
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                TgReserve reserve = new TgReserve();

                TgUser user = UserUtil.getUserFromCookies();
                if (user == null) {
                    return result;
                } else {
                    if (user.getUsergroup().equals(3)) {
                        reserve.setUsername(user.getUsername());
                    }
                }
                if (nickname != null && !"".equals(nickname)) {
   					/*try {
						nickname = new String(nickname.getBytes("iso-8859-1"), "utf-8");
					} catch (Exception e) {
						e.printStackTrace();
					}*/
                    reserve.setNickname(nickname);
                    result.setDefaultModel("nickname", nickname);
                }
                if (startTime != null && !"".equals(startTime)) {
                    reserve.setStartTime(startTime);
                    result.setDefaultModel("startTime", startTime);
                }
                if (endTime != null && !"".equals(endTime)) {
                    reserve.setEndTime(endTime);
                    result.setDefaultModel("endTime", endTime);
                }

                Integer currPage = 1;
                if (vo.getCurrPage() != null && !"".equals(vo.getCurrPage())) {
                    currPage = vo.getCurrPage();
                }
                Integer total = reserveDao.getTrackingCount(reserve);
                Page page = PageUtil.createPage(8, currPage, total);
                List<TgReserve> list = reserveDao.getTrackingByKeyname(reserve, page);
                if (list != null && list.size() > 0) {
                    for (TgReserve res : list) {
                        if (res.getLast_track() != null && !"".equals(res.getLast_track())) {
                            boolean flag = StringUtil.getHanzi(res.getLast_track());
                            if (!flag) {
                                try {
                                    byte[] bytes = StringUtil.hexDecode(res.getLast_track());
                                    String ObjContent = new String(bytes, "UTF-8");
                                    res.setLast_track(ObjContent);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                        }

                        //电话号码
                        if (res.getPhone() != null && !"".equals(res.getPhone())) {
                            Gson gson = new Gson();// new一个Gson对象
                            if (res.getPhone().contains("[{")) {
                                List<Phone> phone = gson.fromJson(res.getPhone(),
                                        new TypeToken<List<Phone>>() {
                                        }.getType());
                                res.setPhlist(phone);
                            }
                        }


                        //时间转换
                        if (res.getLastdate() != null && !"".equals(res.getLastdate())) {
                            String createTime = sdf.format(new Date(res.getLastdate() * 1000));
                            res.setEndtime(createTime);
                        }
                    }
                }
                result.setDefaultModel("list", list);
                result.setDefaultModel("page", page);
                return result;
            }
        });
        return new ModelAndView("system/system_reserve_expired", modelMap);
    }

    //咨询师业务管理--咨询师周统计
    @RequestMapping(value = "/system_person_week_stat")
    public ModelAndView system_person_week_stat(ModelMap modelMap, final BaseVo vo,
                                                HttpServletRequest request, final HttpServletResponse response)
            throws Exception {
        modelMap = WebExecutor.execute(logger, vo, new Biz() {
            public Result process() {
                Result result = new ResultSupport(true);
                return result;
            }
        });
        return new ModelAndView("system/system_person_week_stat", modelMap);
    }

    //咨询师业务管理--咨询师月统计
    @RequestMapping(value = "/system_person_month_stat")
    public ModelAndView system_person_month_stat(ModelMap modelMap, final BaseVo vo,
                                                 HttpServletRequest request, final HttpServletResponse response)
            throws Exception {
        modelMap = WebExecutor.execute(logger, vo, new Biz() {
            public Result process() {
                Result result = new ResultSupport(true);
                return result;
            }
        });
        return new ModelAndView("system/system_person_month_stat", modelMap);
    }

    //咨询师业务管理--中心到访统计
    @RequestMapping(value = "/system_center_stat2")
    public ModelAndView system_center_stat2(ModelMap modelMap, final BaseVo vo,
                                            final HttpServletRequest request, final HttpServletResponse response)
            throws Exception {
        modelMap = WebExecutor.execute(logger, vo, new Biz() {
            public Result process() {
                Result result = new ResultSupport(true);
                try {
                    String time = request.getParameter("start_date");
                    
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                    DecimalFormat fnum = new DecimalFormat("##0.00%");
                    String today = "";
                    String BeforetwoDay = "";
                    String BeforeDay = "";
                    String tommorrow1 = "";
                    String tommorrow2 = "";
                    String tommorrow3 = "";
                    String tommorrow4 = "";
                    String newday = "";
                    Date currentDate = null;
                    if (time != null && !"".equals(time)) {
                        currentDate = sdf.parse(time);// 今天
                        newday = time;
                        Calendar rightNow = Calendar.getInstance();
                        rightNow.setTime(currentDate);
                        rightNow.add(Calendar.DAY_OF_YEAR, -1);
                        String ate = sdf.format(rightNow.getTime());
                        currentDate = sdf.parse(ate);
                    } else {
                        newday = sdf.format(DateUtil.getToDay());
                        currentDate = new Date();
                        Calendar rightNow = Calendar.getInstance();
                        rightNow.setTime(currentDate);
                        rightNow.add(Calendar.DAY_OF_YEAR, -1);
                        String ate = sdf.format(rightNow.getTime());
                        currentDate = sdf.parse(ate);
                    }
                    List<Date> days = DateUtil.dateToWeek(currentDate);
                    BeforetwoDay = sdf.format(days.get(0)).substring(0, 10);
                    BeforeDay = sdf.format(days.get(1)).substring(0, 10);
                    today = sdf.format(days.get(2)).substring(0, 10);
                    tommorrow1 = sdf.format(days.get(3)).substring(0, 10);
                    tommorrow2 = sdf.format(days.get(4)).substring(0, 10);
                    tommorrow3 = sdf.format(days.get(5)).substring(0, 10);
                    tommorrow4 = sdf.format(days.get(6)).substring(0, 10);

                    List<TgOffice> office_List = tgOfficeDao.findAll(TgOffice.class);
                    TgOffice office = new TgOffice();
                    int total = 0;
                    int not = 0;
                    int real = 0;
                    String totrate = "";
                    if (office_List != null && office_List.size() > 0) {
                        for (TgOffice off : office_List) {
                            if (!off.getKeyname().equals("CCEE06DEB51D")) {
                                office.setStaTime(sdf.parse(BeforetwoDay).getTime() / 1000);
                                office.setEnTime(sdf.parse(tommorrow4).getTime() / 1000);
                                office.setRegion(off.getKeyname());
                                int total_reserve = tgOfficeDao.getCenterTotal(office);//总计
                                int not_visit = tgOfficeDao.getCenterNot(office);//未到
                                int real_visit = tgOfficeDao.getCenterReal(office);//实到
                                off.setTotal_reserve(total_reserve);
                                off.setNot_visit(not_visit);
                                off.setReal_visit(real_visit);
                                if (off.getTotal_reserve() > 0) {
                                    int mun = off.getTotal_reserve();
                                    int min = off.getNot_visit();

                                    float scale = (float) min / mun;
                                    String rate = fnum.format(scale);
                                    off.setRate(rate);

                                }
                                //总计
                                total += total_reserve;
                                not += not_visit;
                                real += real_visit;

                                //每天的到访记录
                                List<Cout> colist = new ArrayList<Cout>();
                                if (BeforetwoDay != "") {
                                    //周一
                                    Cout cout = new Cout();
                                    office.setStaTime(sdf.parse(BeforetwoDay).getTime() / 1000);
                                    cout.setCount(tgOfficeDao.getCenterZonji(office));
                                    colist.add(cout);
                                    //周二
                                    Cout cout1 = new Cout();
                                    office.setStaTime(sdf.parse(BeforeDay).getTime() / 1000);
                                    cout1.setCount(tgOfficeDao.getCenterZonji(office));
                                    colist.add(cout1);
                                    //周三
                                    Cout cout2 = new Cout();
                                    office.setStaTime(sdf.parse(today).getTime() / 1000);
                                    cout2.setCount(tgOfficeDao.getCenterZonji(office));
                                    colist.add(cout2);
                                    //周四
                                    Cout cout3 = new Cout();
                                    office.setStaTime(sdf.parse(tommorrow1).getTime() / 1000);
                                    cout3.setCount(tgOfficeDao.getCenterZonji(office));
                                    colist.add(cout3);
                                    //周五
                                    Cout cout4 = new Cout();
                                    office.setStaTime(sdf.parse(tommorrow2).getTime() / 1000);
                                    cout4.setCount(tgOfficeDao.getCenterZonji(office));
                                    colist.add(cout4);
                                    //周六
                                    Cout cout5 = new Cout();
                                    office.setStaTime(sdf.parse(tommorrow3).getTime() / 1000);
                                    cout5.setCount(tgOfficeDao.getCenterZonji(office));
                                    colist.add(cout5);
                                    //周日
                                    Cout cout6 = new Cout();
                                    office.setStaTime(sdf.parse(tommorrow4).getTime() / 1000);
                                    cout6.setCount(tgOfficeDao.getCenterZonji(office));
                                    colist.add(cout6);
                                    off.setCout(colist);
                                }
                            }

                        }
                        if (total > 0) {
                            float scale = (float) not / total;
                            totrate = fnum.format(scale);
                        }

                    }
                    result.setDefaultModel("date3", sdf.format(new Date()));
                    result.setDefaultModel("office_List", office_List);
                    result.setDefaultModel("BeforetwoDay", BeforetwoDay);
                    result.setDefaultModel("BeforeDay", BeforeDay);
                    result.setDefaultModel("today", today);
                    result.setDefaultModel("tommorrow1", tommorrow1);
                    result.setDefaultModel("tommorrow2", tommorrow2);
                    result.setDefaultModel("tommorrow3", tommorrow3);
                    result.setDefaultModel("tommorrow4", tommorrow4);
                    result.setDefaultModel("newday", newday);
                    result.setDefaultModel("office", office);
                    result.setDefaultModel("total", total);
                    result.setDefaultModel("not", not);
                    result.setDefaultModel("totrate", totrate);
                    result.setDefaultModel("real", real);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return result;
            }
        });
        return new ModelAndView("system/system_center_stat", modelMap);
    }

    //咨询师业务管理--中心到访统计
    @RequestMapping(value = "/system_center_stat")
    public ModelAndView system_center_stat(ModelMap modelMap, final BaseVo vo,
    			final HttpServletRequest request, final HttpServletResponse response)
            throws Exception {
        modelMap = WebExecutor.execute(logger, vo, new Biz() {
            public Result process() {
                Result result = new ResultSupport(true);
                try {
                    String time = request.getParameter("start_date");
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                    DecimalFormat df = new DecimalFormat("######0"); //四色五入转换成整数
                    Date currentDate = null;
                    String yearAgo = null;
                    String current = null;
                    String newday = "";
                    if (time != null && !"".equals(time)) {
                        newday = time;
                        /***-----------------------------------------****/
                        currentDate = sdf.parse(time);
                        Calendar cal = Calendar.getInstance();
                        cal.setTime(currentDate);
                        cal.add(Calendar.DATE, 1);
                        //往前推12个月
                        Calendar calendar = Calendar.getInstance();
                        calendar.setTime(currentDate);
                        calendar.add(Calendar.YEAR, -1);//当前时间减去一年，即一年前的时间
                        //calendar.getTime();//获取一年前的时间
                        yearAgo = sdf.format(calendar.getTime());
                        current = sdf.format(cal.getTime());
                        /***-----------------------------------------****/

                    } else {
                        newday = sdf.format(DateUtil.getToDay());
                        /***-----------------------------------------****/
                        //往前推12个月
                        Date date = new Date();//获取当前时间
                        Calendar calendar = Calendar.getInstance();
                        calendar.setTime(date);
                        calendar.add(Calendar.YEAR, -1);//当前时间减去一年，即一年前的时间
                        //calendar.getTime();//获取一年前的时间
                        yearAgo = sdf.format(calendar.getTime());
                        Calendar cal = Calendar.getInstance();
                        cal.setTime(date);
                        cal.add(Calendar.DATE, 1);
                        current = sdf.format(cal.getTime());
                        /***-----------------------------------------****/
                    }

                    TgOffice office = new TgOffice();
                    Integer currPage = 1 ;
    				if (vo.getCurrPage()!=null&&!"".equals(vo.getCurrPage())) {
    					currPage=vo.getCurrPage();
    				}
    				PageObj pageObj = PageUtil.createPages(8, vo.getCurrPage());
    				GridObj mesObj = tgOfficeDao.GetList(office, pageObj);
    				List<TgOffice> office_List = (List<TgOffice>) mesObj.getRoot();
    				Page page = PageUtil.createPage(8, currPage, mesObj.getTotalProperty().intValue());
                    
    				Set<String> citySet = new HashSet<String>();

                    if (office_List != null && office_List.size() > 0) {
                        for (TgOffice off : office_List) {
                        	citySet.add(off.getProvince());
                        	
                            if (!off.getKeyname().equals("CCEE06DEB51D")) {
                                //到访记录
                                List<Cout2> colist = new ArrayList<Cout2>();
                                //全年平均到访率即往前推12个月的到访率
                                double centerMerchant = tgOfficeDao.getCenterMerchant(yearAgo, current, off.getKeyname(), 2);
                                Cout2 cout = new Cout2();
                                cout.setCount(df.format(centerMerchant));
                                colist.add(cout);
                                //全年未到率
                                double centerMerchant1 = tgOfficeDao.getCenterMerchant(yearAgo, current, off.getKeyname(), 3);
                                Cout2 cout1 = new Cout2();
                                cout1.setCount(df.format(centerMerchant1));
                                colist.add(cout1);

                                //半年平均到访
                                Calendar c = Calendar.getInstance();
                                c.setTime(sdf.parse(current));
                                c.add(Calendar.MONTH, -6);
                                double centerMerchant2 = tgOfficeDao.getCenterMerchant(sdf.format(c.getTime()), current, off.getKeyname(), 2);
                                Cout2 cout2 = new Cout2();
                                cout2.setCount(df.format(centerMerchant2));
                                colist.add(cout2);
                                //半年未到率
                                double centerMerchant3 = tgOfficeDao.getCenterMerchant(sdf.format(c.getTime()), current, off.getKeyname(), 3);
                                Cout2 cout3 = new Cout2();
                                cout3.setCount(df.format(centerMerchant3));
                                colist.add(cout3);

                                //上月到访率
                                Calendar c2 = Calendar.getInstance();
                                c2.setTime(sdf.parse(current));
                                c2.add(Calendar.MONTH, -1);
                                double centerMerchant4 = tgOfficeDao.getCenterMerchant(sdf.format(c2.getTime()), current, off.getKeyname(), 2);
                                Cout2 cout4 = new Cout2();
                                cout4.setCount(df.format(centerMerchant4));
                                colist.add(cout4);
                                //上月未到率
                                double centerMerchant5 = tgOfficeDao.getCenterMerchant(sdf.format(c2.getTime()), current, off.getKeyname(), 3);
                                Cout2 cout5 = new Cout2();
                                cout5.setCount(df.format(centerMerchant5));
                                colist.add(cout5);

                                //上周到访率
                                Calendar c3 = Calendar.getInstance();
                                c3.setTime(sdf.parse(current));
                                c3.add(Calendar.DAY_OF_MONTH, -7);
                                double centerMerchant6 = tgOfficeDao.getCenterMerchant(sdf.format(c3.getTime()), current, off.getKeyname(), 2);
                                Cout2 cout6 = new Cout2();
                                cout6.setCount(df.format(centerMerchant6));
                                colist.add(cout6);
                                //上周未到率
                                double centerMerchant7 = tgOfficeDao.getCenterMerchant(sdf.format(c3.getTime()), current, off.getKeyname(), 3);
                                Cout2 cout7 = new Cout2();
                                cout7.setCount(df.format(centerMerchant7));
                                colist.add(cout7);
                                off.setCout2(colist);
                            }
                        }
                    }
                    result.setDefaultModel("newday", newday);
                    result.setDefaultModel("office_List", office_List);
                   result.setDefaultModel("citySet", citySet);
                    result.setDefaultModel("newday2", newday);
                    result.setDefaultModel("page", page);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return result;
            }
        });
        return new ModelAndView("system/system_center_stat2", modelMap);
    }

    //异步获取中心到访统计
    @RequestMapping(value = "/get_center_reserve")
    public ModelAndView get_center_reserve(ModelMap modelMap, final BaseVo vo,
                                           final HttpServletRequest request, HttpServletResponse response)
            throws BaseException {
        modelMap = JsonExecutor.execute(logger, vo, new JsonBiz() {
            public Result process() {
                Result result = new ResultSupport(true);
                String startTime = request.getParameter("date");
                TgReserve reserve = new TgReserve();
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

                String BeforetwoDay = "";
                String tommorrow4 = "";
                Date currentDate = null;
                if (startTime != null && !"".equals(startTime)) {
                    try {
                        currentDate = sdf.parse(startTime);
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }// 今天
                    Calendar rightNow = Calendar.getInstance();
                    rightNow.setTime(currentDate);
                    rightNow.add(Calendar.DAY_OF_YEAR, -1);
                    String ate = sdf.format(rightNow.getTime());
                    try {
                        currentDate = sdf.parse(ate);
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                } else {
                    currentDate = new Date();
                    Calendar rightNow = Calendar.getInstance();
                    rightNow.setTime(currentDate);
                    rightNow.add(Calendar.DAY_OF_YEAR, -1);
                    String ate = sdf.format(rightNow.getTime());
                    try {
                        currentDate = sdf.parse(ate);
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                }
                List<Date> days = DateUtil.dateToWeek(currentDate);
                for (int i = 0; i < days.size(); i++) {
                    BeforetwoDay = sdf.format(days.get(0)).substring(0, 10);
                    tommorrow4 = sdf.format(days.get(6)).substring(0, 10);
                }

                reserve.setStartTime(BeforetwoDay);
                reserve.setEndTime(tommorrow4);
                List<TgReserve> list = reserveDao.getReserveByDate(reserve);
                if (list != null && list.size() > 0) {
                    for (TgReserve res : list) {
                        //设置时间
                        if (res.getDate() != null) {
                            res.setDates(sdf.format(res.getDate()));
                        }

                    }
                }
                result.setDefaultModel("list", list);
                return result;
            }
        });
        return new ModelAndView("", modelMap);
    }


    //咨询师业务管理--关键词统计
    @RequestMapping(value = "/system_keyword_stat")
    public ModelAndView system_keyword_stat(ModelMap modelMap, final BaseVo vo,
                                            final HttpServletRequest request, final HttpServletResponse response)
            throws Exception {
        modelMap = WebExecutor.execute(logger, vo, new Biz() {
            public Result process() {
                Result result = new ResultSupport(true);
                String startTime = request.getParameter("startTime");
                String endTime = request.getParameter("endTime");

                TgClient client = new TgClient();
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

                if (startTime != null && !"".equals(startTime)) {
                    try {
                        client.setsTime(startTime);
                        Date date = sdf.parse(startTime);
                        client.setStartTime(date.getTime() / 1000);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else {
                    Calendar cl = Calendar.getInstance();
                    cl.add(Calendar.WEEK_OF_YEAR, -1);    //一周
                    Date dateFrom = cl.getTime();
                    client.setsTime(sdf.format(dateFrom));
                    client.setStartTime(dateFrom.getTime() / 1000);
                }

                if (endTime != null && !"".equals(endTime)) {
                    try {
                        client.seteTime(endTime);
                        Date date = sdf.parse(endTime);
                        client.setEndTime(date.getTime() / 1000);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else {
                    client.seteTime(sdf.format(new Date()));
                    client.setEndTime(new Date().getTime() / 1000);
                }

                List<TgClient> list = clientDao.getkeyword(client);
                result.setDefaultModel("client", client);
                result.setDefaultModel("list", list);
                return result;
            }
        });
        return new ModelAndView("system/system_keyword_stat", modelMap);
    }

    //客户资源统计
    @RequestMapping(value = "/system_client_count")
    public ModelAndView system_client_count(ModelMap modelMap, final BaseVo vo,
                                            final HttpServletRequest request, HttpServletResponse response)
            throws BaseException {
        modelMap = WebExecutor.execute(logger, vo, new Biz() {
            public Result process() {
                Result result = new ResultSupport(true);
                String startTime = request.getParameter("startTime");
                String endTime = request.getParameter("endTime");
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                try {
                    TgClient client = new TgClient();
                    if (startTime != null && !"".equals(startTime)) {
                        Date stime = sdf.parse(startTime);
                        client.setStartTime(stime.getTime() / 1000);
                    } else {
                        startTime = sdf.format(new Date());
                        client.setStartTime(new Date().getTime() / 1000);
                    }
                    if (endTime != null && !"".equals(endTime)) {
                        Date etime = sdf.parse(endTime);
                        client.setEndTime(etime.getTime() / 1000);
                    } else {
                        endTime = sdf.format(new Date());
                        client.setEndTime(new Date().getTime() / 1000);
                    }
                    Integer count = clientDao.getClientCountByTime(client);

                    result.setDefaultModel("startTime", startTime);
                    result.setDefaultModel("endTime", endTime);
                    result.setDefaultModel("count", count);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                return result;
            }
        });
        return new ModelAndView("system/system_client_count", modelMap);
    }

    /**
     * 原柱状图  一星期 改为24周 线形图
     *
     * @throws BaseException
     */
    @RequestMapping(value = "/system_center_zhuzhuang")
    public ModelAndView system_center_zhuzhuang(ModelMap modelMap, final BaseVo vo,
                final HttpServletRequest request, HttpServletResponse response)
            throws BaseException {
        modelMap = WebExecutor.execute(logger, vo, new Biz() {
            public Result process() {
                Result result = new ResultSupport(true);
                try {
                    String startTime = request.getParameter("startTime");
                    String region = request.getParameter("region");

                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                    if (startTime == null || "".equals(startTime)) {
                        startTime = sdf.format(new Date());
                    }
                    Calendar c = Calendar.getInstance();
                    c.setTime(sdf.parse(startTime));
                    int d = 0;
                    if (c.get(Calendar.DAY_OF_WEEK) == 1) {
                        d = -6;
                    } else {
                        d = 2 - c.get(Calendar.DAY_OF_WEEK);
                    }
                    c.add(Calendar.DAY_OF_WEEK, d);
                    //所在周开始日期
                    //System.out.println(new SimpleDateFormat("yyyy-MM-dd").format(c.getTime()));
                    c.add(Calendar.DAY_OF_WEEK, 7);
                    //所在周结束日期
                    //System.out.println(sdf.format(c.getTime()));
                    //存放日期
                    List<String> weekList = new ArrayList<String>();
                    weekList.add(sdf.format(c.getTime()));
                    //循环获取当前时间或指定时间的24周日期 获取一周的最后一天+一天
                    for (int i = 0; i < 24; i++) {
                        c.add(Calendar.DAY_OF_WEEK, -7);
                        weekList.add(sdf.format(c.getTime()));
                    }
                    StringBuffer weekTotal = new StringBuffer();    //总到的个数
                    StringBuffer weekActual = new StringBuffer();    //实际到的个数
                    StringBuffer weekArray = new StringBuffer();    //每周的最后一天
                    TgReserve reserve = new TgReserve();
                    if (region != null || !"".equals(region)) {
                    	reserve.setRegion(region);
                    }
                    for (int i = weekList.size() - 2; i >= 0; i--) {
                        reserve.setEndTime(weekList.get(i) + ",");
                        Calendar sunday = Calendar.getInstance();
                        sunday.setTime(sdf.parse(weekList.get(i)));
                        sunday.add(Calendar.DAY_OF_WEEK, -1);
                        weekArray.append("'" + sdf.format(sunday.getTime()) + "'" + ","); //防止数字让js解析运算
                        reserve.setStartTime(weekList.get(i + 1));
                        reserve.setState(null);
                        reserve.setNon(0);
                        weekTotal.append(reserveDao.getReserveCountByTime2(reserve) + ",");//getReserveCountByTime方法是根据接待老师查询中心到访 
                        reserve.setState(2);												//getReserveCountByTime2方法是根据测评中心查询中心到访 
                        reserve.setNon(0);
                        weekActual.append(reserveDao.getReserveCountByTime2(reserve) + ",");
                    }
                    result.setDefaultModel("startTime", startTime);
                    result.setDefaultModel("weekTotal", weekTotal.substring(0, weekTotal.length() - 1));
                    result.setDefaultModel("weekActual", weekActual.substring(0, weekActual.length() - 1));
                    result.setDefaultModel("weekList", weekArray.substring(0, weekArray.length() - 1));
                    List<TgOffice> olist = tgOfficeDao.findAll(TgOffice.class);
                    result.setDefaultModel("olist", olist);
                    result.setDefaultModel("region", region);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return result;
            }
        });
        return new ModelAndView("system/system_center_zhuzhuang", modelMap);
    }

    //柱状统计--月
    @RequestMapping(value = "/system_center_zhuzhuang2")
    public ModelAndView system_center_zhuzhuang2(ModelMap modelMap, final BaseVo vo,
                 final HttpServletRequest request, HttpServletResponse response)
            throws BaseException {
        modelMap = WebExecutor.execute(logger, vo, new Biz() {
            public Result process() {
                Result result = new ResultSupport(true);
                try {
                    String time = request.getParameter("time");
                    String region = request.getParameter("region");
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");

                    if (time == null || "".equals(time)) {
                        time = sdf.format(new Date());
                    }
                    List<String> monthList = new ArrayList<String>();//存放25个月份
                    monthList.add(time);
                    Calendar c = Calendar.getInstance();
                    try {
                        c.setTime(sdf.parse(time));
                    } catch (ParseException e1) {
                    }
                    for (int i = 0; i < 24; i++) {
                        c.add(Calendar.MONTH, -1);
                        monthList.add(sdf.format(c.getTime()));
                    }
                    StringBuffer month = new StringBuffer();        //前台显示的月份
                    StringBuffer monthTotal = new StringBuffer();    //每月应到的人数
                    StringBuffer monthActual = new StringBuffer();    //每月实际到的人数
                    TgReserve reserve = new TgReserve();
                    for (int i = monthList.size() - 2; i >= 0; i--) {
                        if (region != null || !"".equals(region)) {
                            reserve.setRegion(region);
                        }
                        reserve.setStartTime(monthList.get(i + 1));
                        reserve.setEndTime(monthList.get(i));
                        month.append("'" + monthList.get(i + 1) + "'" + ",");
                        reserve.setState(null);
                        reserve.setNon(0);

                        monthTotal.append(reserveDao.getReserveCountByTime(reserve) + ",");
                        reserve.setState(2);
                        reserve.setNon(0);
                        monthActual.append(reserveDao.getReserveCountByTime(reserve) + ",");
                    }
                    result.setDefaultModel("month", month.substring(0, month.length() - 1));
                    result.setDefaultModel("monthTotal", monthTotal.substring(0, monthTotal.length() - 1));
                    result.setDefaultModel("monthActual", monthActual.substring(0, monthActual.length() - 1));
                    result.setDefaultModel("time", time);

                    List<TgOffice> olist = tgOfficeDao.findAll(TgOffice.class);
                    result.setDefaultModel("olist", olist);
                    result.setDefaultModel("region", region);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return result;
            }
        });
        return new ModelAndView("system/system_center_zhuzhuang2", modelMap);
    }

    //工作权限的分配
    @RequestMapping(value = "/system_resource_powers")
    public ModelAndView system_resource_powers(ModelMap modelMap, final LoginVo loginVo,
                                               HttpServletRequest request, final HttpServletResponse response)
            throws Exception {
        modelMap = WebExecutor.execute(logger, loginVo, new Biz() {
            public Result process() {
                Result result = new ResultSupport(true);
                TgUserinfo user = new TgUserinfo();
                //user.setJob("网络推广专员");
                List<TgUserinfo> uList = userinfoDao.getUserInfoByUserInfo(user);
					/*
      				user.setJob("网络推广主管");
      				uList.addAll(userinfoDao.getUserInfoByUserInfo(user));

      				user.setJob("市场专员");
      				uList.addAll(userinfoDao.getUserInfoByUserInfo(user));

      				user.setJob("市场主管");
      				uList.addAll(userinfoDao.getUserInfoByUserInfo(user));

      				user.setJob("市场副主管");
      				uList.addAll(userinfoDao.getUserInfoByUserInfo(user));

      				user.setJob("统计专员");
      				uList.addAll(userinfoDao.getUserInfoByUserInfo(user));

      				user.setJob("财务专员");
      				uList.addAll(userinfoDao.getUserInfoByUserInfo(user));

      				user.setJob("财务副主管");*/
                uList.addAll(userinfoDao.getUserInfoByUserInfo(user));

                List<TgPowers> powers = powersDao.findAll(TgPowers.class);

                result.setDefaultModel("powers", powers);
                result.setDefaultModel("uList", uList);
                return result;
            }
        });

        return new ModelAndView("system/statis/system_resource_powers", modelMap);
    }

    //任务量显示
    @RequestMapping(value = "/look_work")
    public ModelAndView look_work(ModelMap modelMap, final LoginVo loginVo,
                                  final HttpServletRequest request, final HttpServletResponse response)
            throws Exception {
        modelMap = WebExecutor.execute(logger, loginVo, new Biz() {
            public Result process() {
                Result result = new ResultSupport(true);
                String date = request.getParameter("start_date");

                SimpleDateFormat df = new SimpleDateFormat("yyyy");
                TgWorkload workload = new TgWorkload();
                try {
                    if (date != null && !"".equals(date)) {
                        workload.setCdate(df.parse(date));
                    } else {
                        workload.setCdate(df.parse(df.format(new Date())));
                    }
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                Calendar ca = Calendar.getInstance();
                List<TgWorkload> list = workloadDao.getWorkload(workload);
                if (list != null && list.size() > 0) {
                    for (TgWorkload lis : list) {
                        ca.setTime(lis.getCdate());
                        ca.set(Calendar.DATE, 1);
                        ca.add(Calendar.MONTH, 1);
                        ca.add(Calendar.DATE, -1);
                        int month = ca.get(Calendar.MONTH) + 1;
                        if (lis.getMonth() != null) {
                            if (month == 1) {
                                lis.setMonths("一月");
                            } else if (month == 2) {
                                lis.setMonths("二月");
                            } else if (month == 3) {
                                lis.setMonths("三月");
                            } else if (month == 4) {
                                lis.setMonths("四月");
                            } else if (month == 5) {
                                lis.setMonths("五月");
                            } else if (month == 6) {
                                lis.setMonths("六月");
                            } else if (month == 7) {
                                lis.setMonths("七月");
                            } else if (month == 8) {
                                lis.setMonths("八月");
                            } else if (month == 9) {
                                lis.setMonths("九月");
                            } else if (month == 10) {
                                lis.setMonths("十月");
                            } else if (month == 11) {
                                lis.setMonths("十一月");
                            } else if (month == 12) {
                                lis.setMonths("十二月");
                            }
                        }
                    }
                }
                if (date != null && !"".equals(date)) {
                    result.setDefaultModel("date", date);
                } else {
                    if (list != null && list.size() > 0) {
                        String date1 = df.format(list.get(0).getCdate());
                        result.setDefaultModel("date", date1);
                    }
                }
                result.setDefaultModel("list", list);
                return result;
            }
        });

        return new ModelAndView("system/system_look_work", modelMap);
    }

    //任务量录入
    @RequestMapping(value = "/work_load")
    public ModelAndView work_load(ModelMap modelMap, final LoginVo loginVo,
                                  final HttpServletRequest request, final HttpServletResponse response)
            throws Exception {
        modelMap = WebExecutor.execute(logger, loginVo, new Biz() {
            public Result process() {
                Result result = new ResultSupport(true);
                String ids = request.getParameter("id");

                TgWorkload workload = new TgWorkload();
                SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM");
                if (ids != null && !"".equals(ids)) {
                    workload = workloadDao.findById(TgWorkload.class, Long.valueOf(ids));
                }
                if (workload.getCdate() != null) {
                    String date = sd.format(workload.getCdate());
                    result.setDefaultModel("date", date);
                }
                result.setDefaultModel("workload", workload);
                return result;
            }
        });
        return new ModelAndView("system/system_work_load", modelMap);
    }

    //根据下拉列表选择地级区域和时间查询
    @RequestMapping(value = "/query_repeat")
    public ModelAndView query_repeat(ModelMap modelMap, final BaseVo vo,
                                     final HttpServletRequest request, final HttpServletResponse response)
            throws Exception {
        modelMap = JsonExecutor.execute(logger, vo, new JsonBiz() {
            public Result process() {
                Result result = new ResultSupport(true);
                String grade = request.getParameter("id");
                String cdate = request.getParameter("cdate");

                TgWorkload workload = new TgWorkload();
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
                workload.setGrade(Integer.parseInt(grade));
                try {
                    workload.setCdate(sdf.parse(cdate));
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                List<TgWorkload> uglist = workloadDao.findByExample(workload);
                if (uglist != null && uglist.size() > 0) {
                    workload = uglist.get(0);
                    result.setDefaultModel("workload", workload);
                } else {
                    result.setDefaultModel("workload", "");
                }
                return result;
            }
        });
        return new ModelAndView("", modelMap);
    }

    //异步添加任务量
    @RequestMapping(value = "/add_work_load")
    public ModelAndView add_work_load(ModelMap modelMap, final BaseVo vo,
                                      final HttpServletRequest request, HttpServletResponse response)
            throws BaseException {
        modelMap = JsonExecutor.execute(logger, vo, new JsonBiz() {
            public Result process() {
                Result result = new ResultSupport(true);
                String grade = request.getParameter("grade");
                String money = request.getParameter("money");
                String regions = request.getParameter("regions");
                String reception = request.getParameter("reception");
                String reserve = request.getParameter("reserve");
                String track = request.getParameter("track");
                String ids = request.getParameter("ids");
                String cdate = request.getParameter("cdate");

                TgWorkload workload = new TgWorkload();
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
                if (money != null && !"".equals(money)) {
                    workload.setTotal_money(Double.parseDouble(money));
                }

                if (reception != null && !"".equals(reception)) {
                    workload.setReception(Integer.parseInt(reception));
                }

                if (reserve != null && !"".equals(reserve)) {
                    workload.setReserve(Integer.parseInt(reserve));
                }

                if (track != null && !"".equals(track)) {
                    workload.setTrack(Integer.parseInt(track));
                }
                TgOffice office = new TgOffice();
                if (grade != null && !"".equals(grade)) {
                    workload.setGrade(Integer.parseInt(grade));
                    if (grade.equals("1")) {
                        String region = "";
                        office.setProvince(regions);
                        List<TgOffice> offList = tgOfficeDao.getOfficeName(office);
                        if (offList != null && !"".equals(offList)) {
                            for (int i = 0; offList.size() > i; i++) {
                                region += offList.get(i).getKeyname() + ",";
                            }
                        }
                        workload.setTotal_region(region.substring(0, region.length() - 1));
                    } else if (grade.equals("2")) {
                        String region = "";
                        office.setProvince(regions);
                        List<TgOffice> offList = tgOfficeDao.getOfficeName(office);
                        if (offList != null && !"".equals(offList)) {
                            for (int i = 0; offList.size() > i; i++) {
                                region += offList.get(i).getKeyname() + ",";
                            }
                        }
                        workload.setTotal_region(region.substring(0, region.length() - 1));
                    } else if (grade.equals("3")) {
                        String region = "";
                        office.setProvince(regions);
                        List<TgOffice> offList = tgOfficeDao.getOfficeName(office);
                        if (offList != null && !"".equals(offList)) {
                            for (int i = 0; offList.size() > i; i++) {
                                region += offList.get(i).getKeyname() + ",";
                            }
                        }
                        workload.setTotal_region(region.substring(0, region.length() - 1));
                    }
                }
                try {
                    if (ids != null && !"".equals(ids)) {
                        workload.setId(Long.valueOf(ids));
                        workload.setCdate(sdf.parse(cdate));
                        workload.setMonth(sdf.parse(cdate).getTime() / 1000);
                        workloadDao.update(workload);
                    } else {
                        workload.setCdate(sdf.parse(cdate));
                        workload.setMonth(sdf.parse(cdate).getTime() / 1000);
                        workloadDao.insert(workload);
                    }
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                return result;
            }
        });
        return new ModelAndView("", modelMap);
    }

    //资源导入权限分配
    @RequestMapping(value = "/system_resource_distr")
    public ModelAndView system_resource_distr(ModelMap modelMap, final LoginVo loginVo,
                                              HttpServletRequest request, final HttpServletResponse response)
            throws Exception {
        modelMap = WebExecutor.execute(logger, loginVo, new Biz() {
            public Result process() {
                Result result = new ResultSupport(true);
                List<TgUserinfo> uList = new ArrayList<TgUserinfo>();
                TgUserinfo user = new TgUserinfo();
                user.setLocked(0);
                user.setJob("网络推广专员");
                List<TgUserinfo> List1 = userinfoDao.getUserInfoByUserInfo(user);
                user.setJob("网络推广主管");
                List<TgUserinfo> List1_1 = userinfoDao.getUserInfoByUserInfo(user);
                user.setJob("网络推广副主管");
                List<TgUserinfo> List1_2 = userinfoDao.getUserInfoByUserInfo(user);
                user.setJob("竞价专员");
                List<TgUserinfo> List1_3 = userinfoDao.getUserInfoByUserInfo(user);

                user.setJob("市场专员");
                List<TgUserinfo> List2 = userinfoDao.getUserInfoByUserInfo(user);
                user.setJob("市场主管");
                List<TgUserinfo> List3 = userinfoDao.getUserInfoByUserInfo(user);
                user.setJob("市场副主管");
                List<TgUserinfo> List4 = userinfoDao.getUserInfoByUserInfo(user);

                uList.addAll(List1);
                uList.addAll(List1_1);
                uList.addAll(List1_2);
                uList.addAll(List1_3);
                uList.addAll(List2);
                uList.addAll(List3);
                uList.addAll(List4);

                TgUserinfo userinfo = new TgUserinfo();
                userinfo.setJob("课程顾问");
                List<TgUserinfo> infoList = userinfoDao.getUserInfoByUserInfo(userinfo);

                result.setDefaultModel("uList", uList);
                result.setDefaultModel("infoList", infoList);
                return result;
            }
        });

        return new ModelAndView("system/statis/system_resource_distr", modelMap);
    }

    //资源导入权限分配
    @RequestMapping(value = "/system_resource_distr2")
    public ModelAndView system_resource_distr2(ModelMap modelMap, final LoginVo loginVo,
                                               HttpServletRequest request, final HttpServletResponse response)
            throws Exception {
        modelMap = WebExecutor.execute(logger, loginVo, new Biz() {
            public Result process() {
                Result result = new ResultSupport(true);
                TgUserinfo userinfo = new TgUserinfo();
                userinfo.setJob("课程顾问");
                List<TgUserinfo> infoList = userinfoDao.getUserInfoByUserInfo(userinfo);

                result.setDefaultModel("infoList", infoList);
                return result;
            }
        });

        return new ModelAndView("system/statis/system_resource_distr2", modelMap);
    }

    //异步获取临时权限
    @RequestMapping(value = "/system_resource_search")
    public ModelAndView system_resource_search(ModelMap modelMap, final BaseVo vo,
                                               final HttpServletRequest request, HttpServletResponse response)
            throws BaseException {
        modelMap = JsonExecutor.execute(logger, vo, new JsonBiz() {
            public Result process() {
                Result result = new ResultSupport(true);
                String username = request.getParameter("username");
                TgUserinfo info = new TgUserinfo();
                info.setUsername(username);
                List<TgUserinfo> list = userinfoDao.findByExample(info);
                if (list != null && list.size() > 0) {
                    String region_temp = list.get(0).getState();
                    result.setDefaultModel("region_temp", region_temp);
                }

                return result;
            }
        });
        return new ModelAndView("", modelMap);
    }


    //异步获取统计权限
    @RequestMapping(value = "/system_resource_power_get")
    public ModelAndView system_resource_power_get(ModelMap modelMap, final BaseVo vo,
                                                  final HttpServletRequest request, HttpServletResponse response)
            throws BaseException {
        modelMap = JsonExecutor.execute(logger, vo, new JsonBiz() {
            public Result process() {
                Result result = new ResultSupport(true);
                String username = request.getParameter("username");
                TgUser user = new TgUser();
                user.setUsername(username);
                List<TgUser> list = userDao.findByExample(user);
                if (list != null && list.size() > 0) {
                    String region_temp = list.get(0).getMenu();
                    result.setDefaultModel("region_temp", region_temp);
                }

                return result;
            }
        });
        return new ModelAndView("", modelMap);
    }

    //异步添加临时权限
    @RequestMapping(value = "/system_resource_go")
    public ModelAndView rsystem_resource_go(ModelMap modelMap, final BaseVo vo,
                                            final HttpServletRequest request, HttpServletResponse response)
            throws BaseException {
        modelMap = JsonExecutor.execute(logger, vo, new JsonBiz() {
            public Result process() {
                Result result = new ResultSupport(true);
                String username = request.getParameter("target");
                String regions = request.getParameter("regions");
                TgUserinfo info = new TgUserinfo();
                info.setUsername(username);
                List<TgUserinfo> list = userinfoDao.findByExample(info);
                if (list != null && list.size() > 0) {
                    info = list.get(0);
                    if (info != null) {
                        info.setState(regions);
                        userinfoDao.update(info);
                    }
                }
                return result;
            }
        });
        return new ModelAndView("", modelMap);
    }

    //咨询师每日上线量设置
    @RequestMapping(value = "/system_consult_distr")
    public ModelAndView system_consult_distr(ModelMap modelMap, final LoginVo loginVo,
                                             HttpServletRequest request, final HttpServletResponse response)
            throws Exception {
        modelMap = WebExecutor.execute(logger, loginVo, new Biz() {
            public Result process() {
                Result result = new ResultSupport(true);
                TgUserinfo userinfo = new TgUserinfo();
                userinfo.setJob("课程顾问");
                List<TgUserinfo> infoList = userinfoDao.getUserInfoByUserInfo(userinfo);

                result.setDefaultModel("infoList", infoList);
                return result;
            }
        });

        return new ModelAndView("system/statis/system_consult_distr", modelMap);
    }

    //异步获取咨询师每日上线
    @RequestMapping(value = "/system_consult_distr_get")
    public ModelAndView system_consult_distr_get(ModelMap modelMap, final BaseVo vo,
                                                 final HttpServletRequest request, HttpServletResponse response)
            throws BaseException {
        modelMap = JsonExecutor.execute(logger, vo, new JsonBiz() {
            public Result process() {
                Result result = new ResultSupport(true);
                String username = request.getParameter("username");
                TgUserinfo info = new TgUserinfo();
                info.setUsername(username);
                List<TgUserinfo> list = userinfoDao.findByExample(info);
                if (list != null && list.size() > 0) {
                    String sxian = list.get(0).getSxian();
                    result.setDefaultModel("sxian", sxian);
                }

                return result;
            }
        });
        return new ModelAndView("", modelMap);
    }

    //异步添加咨询师每日上线量
    @RequestMapping(value = "/system_consult_distr_go")
    public ModelAndView system_consult_distr_go(ModelMap modelMap, final BaseVo vo,
                                                final HttpServletRequest request, HttpServletResponse response)
            throws BaseException {
        modelMap = JsonExecutor.execute(logger, vo, new JsonBiz() {
            public Result process() {
                Result result = new ResultSupport(true);
                String username = request.getParameter("target");
                String sxian = request.getParameter("sxian");
                TgUserinfo info = new TgUserinfo();
                info.setUsername(username);
                List<TgUserinfo> list = userinfoDao.findByExample(info);
                if (list != null && list.size() > 0) {
                    info = list.get(0);
                    if (info != null) {
                        info.setSxian(sxian);
                        userinfoDao.update(info);
                    }
                }
                return result;
            }
        });
        return new ModelAndView("", modelMap);
    }

    //分配权限
    @RequestMapping(value = "/system_powrers_go")
    public ModelAndView system_powrers_go(ModelMap modelMap, final BaseVo vo,
                                          final HttpServletRequest request, HttpServletResponse response)
            throws BaseException {
        modelMap = JsonExecutor.execute(logger, vo, new JsonBiz() {
            public Result process() {
                Result result = new ResultSupport(true);
                String username = request.getParameter("target");
                String sxian = request.getParameter("regions");
                TgUser info = new TgUser();
                info.setUsername(username);
                List<TgUser> list = userDao.findByExample(info);
                if (list != null && list.size() > 0) {
                    info = list.get(0);
                    if (info != null) {
                        info.setMenu(sxian);
                        userDao.update(info);
                    }
                }
                return result;
            }
        });
        return new ModelAndView("", modelMap);
    }

    // 客户资源查询
    //咨询师每日上线量设置
    @RequestMapping(value = "/system_consult_list")
    public ModelAndView system_consult_list(ModelMap modelMap, final LoginVo loginVo,
                                            HttpServletRequest request, final HttpServletResponse response)
            throws Exception {
        modelMap = WebExecutor.execute(logger, loginVo, new Biz() {
            public Result process() {
                Result result = new ResultSupport(true);
                return result;
            }
        });

        return new ModelAndView("system/system_client_list", modelMap);
    }


    @RequestMapping(value = "/system_client_list")
    public ModelAndView system_client_list(ModelMap modelMap,
                                           final BaseVo vo, final HttpServletRequest request,
                                           final HttpServletResponse response) throws Exception {
        modelMap = WebExecutor.execute(logger, vo, new Biz() {
            public Result process() {
                Result result = new ResultSupport(true);
                String nickname = request.getParameter("nickname");
                String stName = request.getParameter("stName");

                String invalid = request.getParameter("btnInvalid");// 有效和无效
                String isBySigned = request.getParameter("isBySigned");// 根据更新时间排序
                String startTime = request.getParameter("startTime");
                String endTime = request.getParameter("endTime");
                String state = request.getParameter("state");
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

                TgClient client = new TgClient();
                if (nickname != null && !"".equals(nickname) && !"null".equals(nickname)) {
                    boolean flag = StringUtil.isNum(nickname);
                    if (flag) {
                        client.setPhone(nickname);
                    } else if(StringUtil.hasDigit(nickname)){
                        client.setPhone(nickname);

            	}else{
                	
            	    client.setNickname(nickname);

                    }
                    result.setDefaultModel("nickname", nickname);
                }
                if (stName != null && !"".equals(stName)
                        && !"null".equals(stName) && !"false".equals(stName)) {
                    client.setStName(stName);
                }
                if (invalid != null && !"".equals(invalid)
                        && !"null".equals(invalid) && !"false".equals(invalid)) {
                    client.setInvalid(0);
                }
                if (startTime != null && !"".equals(startTime)
                        && !"null".equals(startTime)) {
                    try {
                        Date date = sdf.parse(startTime);
                        client.setStartTime(date.getTime() / 1000);
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                }
                if (endTime != null && !"".equals(endTime)
                        && !"null".equals(endTime)) {
                    try {
                        Date date = sdf.parse(endTime);
                        client.setStartTime(date.getTime() / 1000);
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                }
                Integer currPage = 1;
                if (vo.getCurrPage() != null && !"".equals(vo.getCurrPage())) {
                    currPage = vo.getCurrPage();
                }
                Integer total = clientDao.getClientSystem(client);
                Page page = PageUtil.createPage(15, currPage, total);
                List<TgClient> list = new ArrayList<TgClient>();
                if (isBySigned != null && isBySigned.equals("cdate")) {
                    // 根据创建时间排序
                    list = clientDao.getClientBySystem(client, page);
                } else {
                    // 根据更新时间排序
                    list = clientDao.getClientBySystem(client, page);
                }

                if (list != null && list.size() > 0) {
                    TgStudent student = new TgStudent();
                    for (TgClient c : list) {
                        // 时间和备注内容
                        try {
                            if (c.getCdate() != null && !"".equals(c.getCdate())) {
                                String date = sdf2.format(new Date(c.getCdate() * 1000));
                                c.setModeTime(date);
                            }

                            if (c.getRdate() != 0 && !"".equals(c.getRdate())) {
                                String date = sdf2.format(new Date(c.getRdate() * 1000));
                                c.setModeTime(date);
                                String date1 = sdf.format(new Date(c.getCdate() * 1000));
                                c.setDateTime(date1);
                            }

                            if (c.getDescs() != null
                                    && !"".equals(c.getDescs())) {
                                boolean flag = StringUtil.getHanzi(c.getDescs());
                                if (!flag) {
                                    try {
                                        byte[] bytes = StringUtil.hexDecode(c
                                                .getDescs());
                                        String ObjContent = new String(bytes,
                                                "UTF-8");
                                        c.setDescs(ObjContent);
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                }
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        if (c.getPhone() != null && !"".equals(c.getPhone())) {
                            Gson gson = new Gson();// new一个Gson对象
                            if (c.getPhone().contains("[{")) {
                                List<Phone> phone = gson.fromJson(c.getPhone(),
                                        new TypeToken<List<Phone>>() {
                                        }.getType());
                                c.setPhlist(phone);
// 								c.setPhone(c.getPhlist().get(0).getPhone());
                            }
                        }
                        // 学生
                        if (c.getKeyname() != null
                                && !"".equals(c.getKeyname())) {
                            student.setPkey(c.getKeyname());
                            List<TgStudent> studentList = studentDao
                                    .findByExample(student);
                            if (studentList != null && studentList.size() > 0) {
                                String stu = "";
                                String context = "";

                                for (int i = 0; i < studentList.size(); i++) {
                                    String age = studentList.get(i).getAge();
                                    if (age == null) {
                                        age = "0";
                                    }
                                    stu += studentList.get(i).getNickname()
                                            + "<span class=\"caption\">("
                                            + age + "岁"
                                            + ")</span>,";

                                    String con = "";
                                    String Contentq = "";
                                    if (studentList.get(i).getFeature() != null && !"".equals(studentList.get(i).getFeature())) {
                                        boolean flag1 = StringUtil.getHanzi(studentList.get(i).getFeature());
                                        if (!flag1) {
                                            byte[] bytes = StringUtil.hexDecode(studentList.get(i).getFeature());
                                            try {
                                                Contentq += new String(bytes, "UTF-8");
                                            } catch (UnsupportedEncodingException e) {
                                                e.printStackTrace();
                                            }
                                            if (Contentq != null && !"".equals(Contentq)) {
                                                con = studentList.get(i).getNickname() + ":(" + Contentq + ")";
                                            }
                                        } else {
                                            if (studentList.get(i).getFeature() != null && !"".equals(studentList.get(i).getFeature())) {
                                                con = studentList.get(i).getNickname() + ":(" + studentList.get(i).getFeature() + ")";
                                            }
                                        }
                                        if (con != null && !"".equals(con)) {
                                            context = context + con + "</br>";
                                        }
                                    }
                                    c.setFeature(context);
                                }
                                c.setStudent(stu);
                            }
                        }
                    }
                }
                result.setDefaultModel("stName", stName);

                result.setDefaultModel("invalid", invalid);
                result.setDefaultModel("isBySigned", isBySigned);
                result.setDefaultModel("startTime", startTime);
                result.setDefaultModel("endTime", endTime);
                result.setDefaultModel("state", state);
                result.setDefaultModel("page", page);
                result.setDefaultModel("list", list);

                return result;
            }
        });
        return new ModelAndView("system/system_client_list", modelMap);
    }

    @RequestMapping(value = "/map")
    public ModelAndView map(ModelMap modelMap, final LoginVo loginVo,
                            HttpServletRequest request, final HttpServletResponse response)
            throws Exception {
        modelMap = WebExecutor.execute(logger, loginVo, new Biz() {
            public Result process() {
                Result result = new ResultSupport(true);
                return result;
            }
        });

        return new ModelAndView("system/map/map", modelMap);
    }

    //管理员评分
    @RequestMapping(value = "/query_user")
    public ModelAndView query_user(ModelMap modelMap, final BaseVo vo,
        final HttpServletRequest request, final HttpServletResponse response)
            throws Exception {
        modelMap = JsonExecutor.execute(logger, vo, new JsonBiz() {
            public Result process() {
                Result result = new ResultSupport(true);
                String username = request.getParameter("username");
                String cdate = request.getParameter("cdate");

                return result;
            }
        });
        return new ModelAndView("", modelMap);
    }


   /* //查询全部老师评分
    @RequestMapping(value = "/look_grade")
    public ModelAndView look_grade(ModelMap modelMap, final BaseVo vo,
                                   final HttpServletRequest request, final HttpServletResponse response)
            throws Exception {
        modelMap = WebExecutor.execute(logger, vo, new Biz() {
            public Result process() {
                Result result = new ResultSupport(true);

                String start = request.getParameter("start");//查询时间
                String username = request.getParameter("username");//查询姓名
                String flag = request.getParameter("flag");//查询姓名
                TgUser user = UserUtil.getUserFromCookies();
                TgUsergrade usergrade = new TgUsergrade();
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
                usergrade.setMarker(user.getUsername());
                try {
                    if (start != null && !"".equals(start)) {
                        usergrade.setCdate(sdf.parse(start));
                        result.setDefaultModel("cdate", start);
                    } else {
                        usergrade.setCdate(sdf.parse(sdf.format(new Date())));
                        result.setDefaultModel("cdate", sdf.format(new Date()));
                    }
                    if (username != null && !"".equals(username)) {
                        usergrade.setUsername(username);
                        result.setDefaultModel("username", username);
                    }
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                Integer currPage = 1;
                if (vo.getCurrPage() != null && !"".equals(vo.getCurrPage())) {
                    currPage = vo.getCurrPage();
                }
                Integer total = usergradeDao.getUsergradeCount(usergrade);
                Page page = PageUtil.createPage(8, currPage, total);
                List<TgUsergrade> list = usergradeDao.getUsergradelist(usergrade, page);
                if (flag.equals("1")){
                    List<SalesExecutive> uList = salesExecutiveDao.getSalesExecutiveList(new SalesExecutive(), new Page());
                    result.setDefaultModel("uList", uList);
                }
               else  if (flag.equals("2")){
                    TgUserinfo useriInfo  = new TgUserinfo();
                    useriInfo.setJob("课程顾问");
                    useriInfo.setRegion(user.getRegion());
                    List<TgUserinfo> uList =userinfoDao.getUserInfoByUserInfo(useriInfo);
                    result.setDefaultModel("uList",uList);
                }else if (flag.equals("3")){
                    SalesExecutive salesExecutive = new SalesExecutive();
                    salesExecutive.setUsername(user.getUsername());
                    List<SalesExecutive> salesExecutiveByuser = salesExecutiveDao.getSalesExecutiveByuser(salesExecutive);
                    List<TgUserinfo> uList =new ArrayList<TgUserinfo>();
                    if (uList!=null && uList.size()>0) {
                        try {
                            JSONArray jsonArray = new JSONArray(salesExecutiveByuser.get(0).getChilden());
                            for (int i = 0; i < jsonArray.length(); i++) {
                                org.json.JSONObject job = jsonArray.getJSONObject(i);
                                TgUserinfo tgUserInfo = new TgUserinfo();
                                tgUserInfo.setUsername(job.get("username") + "");
                                tgUserInfo.setNickname(job.get("name") + "");
                                uList.add(tgUserInfo);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        result.setDefaultModel("uList", uList);
                    }
                }

                result.setDefaultModel("page", page);
                result.setDefaultModel("list", list);
                result.setDefaultModel("flag", flag);
                return result;
            }
        });
        return new ModelAndView("system/system_look_grade", modelMap);
    }*/

    //缴费列表
    @RequestMapping(value = "/system_reception_moneylist")
    public ModelAndView system_reception_moneylist(ModelMap modelMap, final BaseVo vo,
                                                   final HttpServletRequest request, final HttpServletResponse response)
            throws Exception {
        modelMap = WebExecutor.execute(logger, vo, new Biz() {
            public Result process() {
                Result result = new ResultSupport(true);
                String startTime = request.getParameter("startTime");
                String endTime = request.getParameter("endTime");
                String name1 = request.getParameter("name1");
                String bank_id = request.getParameter("bank_id");
                String center = request.getParameter("center");
                String knickname = request.getParameter("knickname");
                String snickname = request.getParameter("snickname");
                String rkey = request.getParameter("rkey");
                String worth = request.getParameter("worth");
                String phone = request.getParameter("phone");
                String source = request.getParameter("source");
                String stnickname = request.getParameter("stnickname");
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

                TgReception reception = new TgReception();
                TgUser user = UserUtil.getUserFromCookies();

                if ((startTime != null && !startTime.equals("")) ||
                        (endTime != null && !endTime.equals(""))) {
                    try {
                        reception.setStartTime(sdf.parse(startTime).getTime() / 1000);
                        reception.setEndTime(DateUtil.getTommorrowDay1(sdf.parse(endTime)).getTime() / 1000);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else {
                    try {
                        startTime = sdf.format(DateUtil.getMonthFirst(sdf.format(new Date())));
                        endTime = sdf.format(DateUtil.getMonthLast(sdf.format(new Date())));
                        reception.setStartTime(sdf.parse(sdf.format(DateUtil.getMonthFirst(sdf.format(new Date())))).getTime() / 1000);
                        reception.setEndTime(DateUtil.getTommorrowDay1(sdf.parse(sdf.format(DateUtil.getMonthLast(sdf.format(new Date()))))).getTime() / 1000);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

                if (center != null && !center.equals("")) {
                    reception.setRegionns(center);
                }
                if (name1 != null && !name1.equals("")) {
                    reception.setName1(name1);
                }
                if (bank_id != null && !bank_id.equals("")) {
                    reception.setBank_id1(bank_id);
                }

                if (user == null) {
                    return result;
                } else if (user.getUsergroup() == 3) {
                    reception.setUsername(user.getUsername());
                }

                if (knickname != null && !"".equals(knickname)) {
                    reception.setKnickname(knickname);
                }
                if (snickname != null && !"".equals(snickname)) {
                    reception.setSnickname(snickname);
                }
                if (stnickname != null && !"".equals(stnickname)) {
                    reception.setStnickname(stnickname);
                }
                if (rkey != null && !"".equals(rkey)) {
                    if (rkey.equals("1")) {
                        reception.setRkey1(rkey);
                    } else if (rkey.equals("2")) {
                        reception.setRkey2(rkey);
                    }
                    reception.setRkey(rkey);
                }
                if (source != null && !"".equals(source)) {
                    reception.setSource(source);
                }

                if (worth != null && !"".equals(worth)) {
                    reception.setWorth(Integer.parseInt(worth));
                }
                if (phone != null && !"".equals(phone)) {
                    reception.setPhone(phone);
                }
                List<TgReception> list = new ArrayList<TgReception>();
                List<TgReception> list1 = receptionDao.getReceptionByStatis1(reception);
                List<TgReception> list2 = receptionDao.getReceptionByStatis2(reception);
                List<TgReception> list3 = receptionDao.getReceptionByStatis3(reception);
                list.addAll(list1);
                list.addAll(list2);
                list.addAll(list3);
                Gson gson = new Gson();
                if (list != null && list.size() > 0) {
                    Collections.sort(list, new Comparator<TgReception>() {
                        @Override
                        public int compare(TgReception o1, TgReception o2) {
                            // TODO Auto-generated method stub
                            return (int) ((int) (o2.getMoneydate().getTime() / 1000) - o1.getMoneydate().getTime() / 1000);
                        }
                    });

                    for (TgReception rece : list) {
                        //日期转换
                        if (rece.getDate() != null && !"".equals(rece.getDate())) {
                            String gtime = sdf.format(new Date(rece.getDate() * 1000));
                            rece.setGtime(gtime);
                        }
                        //联系方式
                        if (rece.getPhone() != null && !"".equals(rece.getPhone())) {
                            if (rece.getPhone().contains("[{")) {
                                List<Phone> phone1 = gson.fromJson(rece.getPhone(),
                                        new TypeToken<List<Phone>>() {
                                        }.getType());
                                rece.setPhlist(phone1);
                            }
                        }
                    }
                }

                List<TgOffice> rList = tgOfficeDao.findAll(TgOffice.class);
                TgMethod method = new TgMethod();
                List<TgMethod> mList = methodDao.getBankIdBydis(method);

                result.setDefaultModel("reception", reception);
                result.setDefaultModel("rList", rList);
                result.setDefaultModel("mList", mList);
                result.setDefaultModel("list", list);
                result.setDefaultModel("knickname", knickname);
                result.setDefaultModel("snickname", snickname);
                result.setDefaultModel("rkey", rkey);
                result.setDefaultModel("startTime", startTime);
                result.setDefaultModel("endTime", endTime);
                result.setDefaultModel("bank_id", bank_id);
                result.setDefaultModel("name1", name1);
                result.setDefaultModel("center", center);
                result.setDefaultModel("phone", phone);
                result.setDefaultModel("source", source);
                result.setDefaultModel("stnickname", stnickname);
                return result;
            }
        });
        return new ModelAndView("system/statis/system_reception_moneylist", modelMap);
    }

    //下载缴费记录
    @RequestMapping(value = "/xiaz_reception_money")
    public ModelAndView xiaz_reception_money(ModelMap modelMap, final BaseVo vo,
                                             final HttpServletRequest request, final HttpServletResponse response)
            throws Exception {
        modelMap = JsonExecutor.execute(logger, vo, new JsonBiz() {
            public Result process() {
                Result result = new ResultSupport(true);
                String startTime = request.getParameter("startTime");
                String endTime = request.getParameter("endTime");
                String name1 = request.getParameter("name1");
                String bank_id = request.getParameter("bank_id");
                String center = request.getParameter("center");
                String knickname = request.getParameter("knickname");
                String snickname = request.getParameter("snickname");
                String rkey = request.getParameter("rkey");
                String worth = request.getParameter("worth");
                String phone = request.getParameter("phone");
                String source = request.getParameter("source");
                String stnickname = request.getParameter("stnickname");
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

                TgReception reception = new TgReception();
                TgUser user = UserUtil.getUserFromCookies();

                if ((startTime != null && !startTime.equals("")) ||
                        (endTime != null && !endTime.equals(""))) {
                    try {
                        reception.setStartTime(sdf.parse(startTime).getTime() / 1000);
                        reception.setEndTime(sdf.parse(endTime).getTime() / 1000);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else {
                    try {
                        startTime = sdf.format(DateUtil.getMonthFirst(sdf.format(new Date())));
                        endTime = sdf.format(DateUtil.getMonthLast(sdf.format(new Date())));
                        reception.setStartTime(DateUtil.getBeforeDay(sdf.parse(sdf.format(DateUtil.getMonthFirst(sdf.format(new Date()))))).getTime() / 1000);
                        reception.setEndTime(DateUtil.getTommorrowDay1(sdf.parse(sdf.format(DateUtil.getMonthLast(sdf.format(new Date()))))).getTime() / 1000);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

                if (center != null && !center.equals("")) {
                    reception.setRegionns(center);
                }
                if (name1 != null && !name1.equals("")) {
                    reception.setName1(name1);
                }
                if (bank_id != null && !bank_id.equals("")) {
                    reception.setBank_id1(bank_id);
                }

                if (user == null) {
                    return result;
                } else if (user.getUsergroup() == 3) {
                    reception.setUsername(user.getUsername());
                }

                if (knickname != null && !"".equals(knickname)) {
                    reception.setKnickname(knickname);
                }
                if (snickname != null && !"".equals(snickname)) {
                    reception.setSnickname(snickname);
                }
                if (stnickname != null && !"".equals(stnickname)) {
                    reception.setStnickname(stnickname);
                }
                if (rkey != null && !"".equals(rkey)) {
                    if (rkey.equals("1")) {
                        reception.setRkey1(rkey);
                    } else if (rkey.equals("2")) {
                        reception.setRkey2(rkey);
                    }
                    reception.setRkey(rkey);
                }
                if (source != null && !"".equals(source)) {
                    reception.setSource(source);
                }

                if (worth != null && !"".equals(worth)) {
                    reception.setWorth(Integer.parseInt(worth));
                }
                if (phone != null && !"".equals(phone)) {
                    reception.setPhone(phone);
                }
                List<TgReception> list = new ArrayList<TgReception>();
                List<TgReception> list1 = receptionDao.getReceptionByStatis1(reception);
                List<TgReception> list2 = receptionDao.getReceptionByStatis2(reception);
                List<TgReception> list3 = receptionDao.getReceptionByStatis3(reception);
                list.addAll(list1);
                list.addAll(list2);
                list.addAll(list3);
                Gson gson = new Gson();
                if (list != null && list.size() > 0) {
                    Collections.sort(list, new Comparator<TgReception>() {
                        @Override
                        public int compare(TgReception o1, TgReception o2) {
                            // TODO Auto-generated method stub
                            return (int) ((int) (o2.getMoneydate().getTime() / 1000) - o1.getMoneydate().getTime() / 1000);
                        }
                    });

                    for (TgReception rece : list) {
                        //日期转换
                        if (rece.getDate() != null && !"".equals(rece.getDate())) {
                            String gtime = sdf.format(new Date(rece.getDate() * 1000));
                            rece.setGtime(gtime);
                        }
                        //联系方式
                        if (rece.getPhone() != null && !"".equals(rece.getPhone())) {
                            if (rece.getPhone().contains("[{")) {
                                List<Phone> phone1 = gson.fromJson(rece.getPhone(),
                                        new TypeToken<List<Phone>>() {
                                        }.getType());
                                rece.setPhlist(phone1);
                            }
                        }
                    }
                }

                String name = WriterExcel.writeExcelClientMoneyByTime(list, startTime, endTime);

                result.setDefaultModel("name", name);
                return result;
            }
        });
        return new ModelAndView("", modelMap);
    }


    /**
     * 异步修改来源名称
     *
     * @param regionns 来源
     * @param client   tg_client keyname
     */
    @RequestMapping(value = "system_ajaxedit_source")
    public void ajaxEditSource(String regionns, String client, HttpServletResponse response) {
        try {
            if (!StringUtil.isEmpty(regionns) && !StringUtil.isEmpty(client)) {
                Integer state = clientDao.editSourceByKeyname(client, regionns);
                PrintWriter out = response.getWriter();
                out.print(state);
            }
        } catch (Exception e) {
        }
    }

    /**
     * 异步获取当前城市中心
     */
    @RequestMapping(value = "system_getcorename")
    public void ajaxGetCoreName(String cityName, HttpServletResponse response) {
        try {
            List<TgOffice> coreNameByCity = tgOfficeDao.getCoreNameByCity(cityName);
            if (coreNameByCity != null) {
                JSONArray json = new JSONArray();
                for (TgOffice tgOffice : coreNameByCity) {
                    JSONObject jo = new JSONObject();
                    jo.put("name", tgOffice.getName());
                    jo.put("keyname", tgOffice.getKeyname());
                    json.put(jo);
                }
                response.setCharacterEncoding("UTF-8");
                PrintWriter out = response.getWriter();
                out.print(json);
            }
        } catch (Exception e) {
        }
    }

    /**
     * 异步查询选中的城市和中心 到访率
     */
    @RequestMapping(value = "system_select_24week")
    public void select24Week(String cityName, String keyname, String date, HttpServletResponse response) {
        try {
            List<String> weekList = get24Week(date);
            List<TgOffice> coreNameByCity = tgOfficeDao.getCoreNameByCity(cityName);//城市所对应的所有中心keyname
            StringBuffer coreKeynames = new StringBuffer();
            for (TgOffice tgOffice : coreNameByCity) {
                coreKeynames.append("'" + tgOffice.getKeyname() + "'" + ",");
            }
            StringBuffer week = new StringBuffer();
            StringBuffer cityRate = new StringBuffer();        //城市到访率
            StringBuffer cityNotRate = new StringBuffer();    //城市未到率
            StringBuffer coreRate = new StringBuffer();        //中心到访率
            StringBuffer corenotRate = new StringBuffer();    //中心未到率
            //查询当前城市的到访率和未到率
            for (int i = weekList.size() - 2; i >= 0; i--) {
                week.append(weekList.get(i) + ",");
                cityRate.append(tgOfficeDao.getCurrentCityMerchant(weekList.get(i + 1), weekList.get(i), coreKeynames.substring(0, coreKeynames.length() - 1), 2) + ",");
                cityNotRate.append(tgOfficeDao.getCurrentCityMerchant(weekList.get(i + 1), weekList.get(i), coreKeynames.substring(0, coreKeynames.length() - 1), 3) + ",");
                coreRate.append(tgOfficeDao.getCenterMerchant(weekList.get(i + 1), weekList.get(i), keyname, 2) + ",");
                corenotRate.append(tgOfficeDao.getCenterMerchant(weekList.get(i + 1), weekList.get(i), keyname, 3) + ",");
            }
            response.setContentType("text/json;charset=UTF-8");
            PrintWriter out = response.getWriter();
            JSONArray jsonArray = new JSONArray();
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("week", week.substring(0, week.length() - 1));
            jsonObject.put("cityRate", cityRate.substring(0, cityRate.length() - 1));
            jsonObject.put("cityNotRate", cityNotRate.substring(0, cityNotRate.length() - 1));
            jsonObject.put("coreRate", coreRate.substring(0, coreRate.length() - 1));
            jsonObject.put("corenotRate", corenotRate.substring(0, corenotRate.length() - 1));
            jsonArray.put(jsonObject);
            out.print(jsonArray);
        } catch (Exception e) {

        }
    }

    //获取24周
    public List<String> get24Week(String date) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        if (date == null || date == "") {
            date = sdf.format(new Date());
        }
        try {
            Calendar c = Calendar.getInstance();
            c.setTime(sdf.parse(date));
            int d = 0;
            if (c.get(Calendar.DAY_OF_WEEK) == 1) {
                d = -6;
            } else {
                d = 2 - c.get(Calendar.DAY_OF_WEEK);
            }
            c.add(Calendar.DAY_OF_WEEK, d);
            //所在周开始日期
            //System.out.println(new SimpleDateFormat("yyyy-MM-dd").format(c.getTime()));
            c.add(Calendar.DAY_OF_WEEK, 7);
            //所在周结束日期
            //System.out.println(sdf.format(c.getTime()));
            //存放日期
            List<String> weekList = new ArrayList<String>();
            weekList.add(sdf.format(c.getTime()));
            //循环获取当前时间或指定时间的24周日期 获取一周的最后一天+一天
            for (int i = 0; i < 24; i++) {
                c.add(Calendar.DAY_OF_WEEK, -7);
                weekList.add(sdf.format(c.getTime()));
            }
            return weekList;
        } catch (Exception e) {
            return null;
        }
    }

    public Integer comparisonDate(Date dt1, Date dt2) {
        try {
            if (dt1.getTime() >= dt2.getTime()) {
                return 1;
            } else if (dt1.getTime() < dt2.getTime()) {
                return -1;
            } else {
                return 0;
            }
        } catch (Exception exception) {
            exception.printStackTrace();
        }
        return 0;
    }


    //咨询师业务管理--中心到访统计
    @RequestMapping(value = "/system_center_stat3")
    public ModelAndView system_center_stat3(ModelMap modelMap, final BaseVo vo,
                                            final HttpServletRequest request, final HttpServletResponse response)
            throws Exception {
        modelMap = WebExecutor.execute(logger, vo, new Biz() {
            public Result process() {
                Result result = new ResultSupport(true);
                try {
                    String time = request.getParameter("start_date");
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                    DecimalFormat fnum = new DecimalFormat("##0.00%");
                    String today = null;
                    String BeforetwoDay = null;
                    String BeforeDay = null;
                    String tommorrow1 = null;
                    String tommorrow2 = null;
                    String tommorrow3 = null;
                    String tommorrow4 = null;
                    String newday = null;
                    Date currentDate = null;
                    if (time != null && !"".equals(time)) {
                        currentDate = sdf.parse(time);// 今天
                        newday = time;
                        Calendar rightNow = Calendar.getInstance();
                        rightNow.setTime(currentDate);
                        rightNow.add(Calendar.DAY_OF_YEAR, -1);
                        String ate = sdf.format(rightNow.getTime());
                        currentDate = sdf.parse(ate);
                    } else {
                        newday = sdf.format(DateUtil.getToDay());
                        currentDate = new Date();
                        Calendar rightNow = Calendar.getInstance();
                        rightNow.setTime(currentDate);
                        rightNow.add(Calendar.DAY_OF_YEAR, -1);
                        String ate = sdf.format(rightNow.getTime());
                        currentDate = sdf.parse(ate);
                    }
                    List<Date> days = DateUtil.dateToWeek(currentDate);
                    if (comparisonDate(sdf.parse(newday), days.get(0)) == 1) {
                        BeforetwoDay = sdf.format(days.get(0)).substring(0, 10);
                    }
                    if (comparisonDate(sdf.parse(newday), days.get(1)) == 1) {
                        BeforeDay = sdf.format(days.get(1)).substring(0, 10);
                    }
                    if (comparisonDate(sdf.parse(newday), days.get(2)) == 1) {
                        today = sdf.format(days.get(2)).substring(0, 10);
                    }
                    if (comparisonDate(sdf.parse(newday), days.get(3)) == 1) {
                        tommorrow1 = sdf.format(days.get(3)).substring(0, 10);
                    }
                    if (comparisonDate(sdf.parse(newday), days.get(4)) == 1) {
                        tommorrow2 = sdf.format(days.get(4)).substring(0, 10);
                    }
                    if (comparisonDate(sdf.parse(newday), days.get(5)) == 1) {
                        tommorrow3 = sdf.format(days.get(5)).substring(0, 10);
                    }
                    if (comparisonDate(sdf.parse(newday), days.get(6)) == 1) {
                        tommorrow4 = sdf.format(days.get(6)).substring(0, 10);
                    }


                    List<TgOffice> office_List = tgOfficeDao.findAll(TgOffice.class);
                    TgOffice office = new TgOffice();
                    int total = 0;
                    int not = 0;
                    int real = 0;
                    String totrate = "";
                    if (office_List != null && office_List.size() > 0) {
                        for (TgOffice off : office_List) {
                            if (!off.getKeyname().equals("CCEE06DEB51D")) {
                                office.setStaTime(sdf.parse(BeforetwoDay).getTime() / 1000);
                                office.setEnTime(sdf.parse(newday).getTime() / 1000);
                                office.setRegion(off.getKeyname());
                                int total_reserve = tgOfficeDao.getCenterTotal(office);
                                int not_visit = tgOfficeDao.getCenterNot(office);
                                int real_visit = tgOfficeDao.getCenterReal(office);
                                off.setTotal_reserve(total_reserve);
                                off.setNot_visit(not_visit);
                                off.setReal_visit(real_visit);
                                if (off.getTotal_reserve() > 0) {
                                    int mun = off.getTotal_reserve();
                                    int min = off.getNot_visit();

                                    float scale = (float) min / mun;
                                    String rate = fnum.format(scale);
                                    off.setRate(rate);

                                }
                                //总计
                                total += total_reserve;
                                not += not_visit;
                                real += real_visit;

                                //每天的到访记录
                                List<Cout> colist = new ArrayList<Cout>();
								/*if(BeforetwoDay!=""){*/
                                //周一
                                if (BeforetwoDay != null) {
                                    Cout cout = new Cout();
                                    office.setStaTime(sdf.parse(BeforetwoDay).getTime() / 1000);
                                    cout.setCount(tgOfficeDao.getCenterZonji(office));
                                    colist.add(cout);
                                }
                                if (BeforeDay != null) {
                                    //周二
                                    Cout cout1 = new Cout();
                                    office.setStaTime(sdf.parse(BeforeDay).getTime() / 1000);
                                    cout1.setCount(tgOfficeDao.getCenterZonji(office));
                                    colist.add(cout1);
                                }
                                if (today != null) {
                                    //周三
                                    Cout cout2 = new Cout();
                                    office.setStaTime(sdf.parse(today).getTime() / 1000);
                                    cout2.setCount(tgOfficeDao.getCenterZonji(office));
                                    colist.add(cout2);
                                }
                                if (tommorrow1 != null) {
                                    //周四
                                    Cout cout3 = new Cout();
                                    office.setStaTime(sdf.parse(tommorrow1).getTime() / 1000);
                                    cout3.setCount(tgOfficeDao.getCenterZonji(office));
                                    colist.add(cout3);
                                }
                                if (tommorrow2 != null) {
                                    //周五
                                    Cout cout4 = new Cout();
                                    office.setStaTime(sdf.parse(tommorrow2).getTime() / 1000);
                                    cout4.setCount(tgOfficeDao.getCenterZonji(office));
                                    colist.add(cout4);
                                }
                                if (tommorrow3 != null) {
                                    //周六
                                    Cout cout5 = new Cout();
                                    office.setStaTime(sdf.parse(tommorrow3).getTime() / 1000);
                                    cout5.setCount(tgOfficeDao.getCenterZonji(office));
                                    colist.add(cout5);
                                }
                                if (tommorrow4 != null) {
                                    //周日
                                    Cout cout6 = new Cout();
                                    office.setStaTime(sdf.parse(tommorrow4).getTime() / 1000);
                                    cout6.setCount(tgOfficeDao.getCenterZonji(office));
                                    colist.add(cout6);

                                }
                                off.setCout(colist);
							/*	}*/
                            }

                        }
                        if (total > 0) {
                            float scale = (float) not / total;
                            totrate = fnum.format(scale);
                        }

                    }
                    result.setDefaultModel("office_List", office_List);

                    result.setDefaultModel("BeforetwoDay", BeforetwoDay);
                    result.setDefaultModel("BeforeDay", BeforeDay);
                    result.setDefaultModel("today", today);
                    result.setDefaultModel("tommorrow1", tommorrow1);
                    result.setDefaultModel("tommorrow2", tommorrow2);
                    result.setDefaultModel("tommorrow3", tommorrow3);
                    result.setDefaultModel("tommorrow4", tommorrow4);
                    result.setDefaultModel("newday", newday);
                    result.setDefaultModel("office", office);
                    result.setDefaultModel("total", total);
                    result.setDefaultModel("not", not);
                    result.setDefaultModel("totrate", totrate);
                    result.setDefaultModel("real", real);
                    result.setDefaultModel("size", office_List.get(0).getCout().size());

                } catch (Exception e) {
                    e.printStackTrace();
                }
                return result;
            }
        });
        return new ModelAndView("system/system_center_stat3", modelMap);
    }
    
    //中心主任评分
    @RequestMapping(value = "/sys_markList")
    public ModelAndView salesExecutive(ModelMap modelMap, final BaseVo vo,
          final HttpServletRequest request, final HttpServletResponse response)
            throws Exception {
        modelMap = WebExecutor.execute(logger, vo, new Biz() {
            public Result process() {
                Result result = new ResultSupport(true);
                String nickname2 = request.getParameter("nickName");
  				String date = request.getParameter("date");

  				TgUsergrade usergrade = new TgUsergrade();
  				if (!StringUtil.isEmpty(nickname2)){
  					usergrade.setNickname2(nickname2);
  				}
  				if (!StringUtil.isEmpty(date)){
  					usergrade.setDate(date);
  				}
  				Integer currPage = 1;
  				if (vo.getCurrPage() != null && !"".equals(vo.getCurrPage())) {
  					currPage = vo.getCurrPage();
  				}
  				Integer total = usergradeDao.getUsergradeCount(usergrade);
  				Page page = PageUtil.createPage(8, currPage, total);
  				List<TgUsergrade> list = usergradeDao.getUsergradelist(usergrade, page);
  				
				result.setDefaultModel("page", page);
				result.setDefaultModel("list", list);
                return result;
            }
        });
        return new ModelAndView("consultant/mark/sys_markList", modelMap);
    }

    //咨询师业务管理--客户接待数据管理
    @RequestMapping(value = "/uploadToExcel")
    public String uploadToExcel(final BaseVo vo, final HttpServletRequest request, final HttpServletResponse response)
            throws Exception {
        String knickname = request.getParameter("knickname");
        String snickname = request.getParameter("snickname");
        String rkey = request.getParameter("rkey");
        String worth = request.getParameter("worth");
        String phone = request.getParameter("phone");
        String email = request.getParameter("email");
        String qq = request.getParameter("qq");
        String source = request.getParameter("source");
        String stnickname = request.getParameter("stnickname");
        String time = request.getParameter("time");

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        TgReception reception = new TgReception();
        TgUser user = UserUtil.getUserFromCookies();
        if (user == null) {
            return null;
        } else if (user.getUsergroup() == 3) {
            reception.setUsername(user.getUsername());
        }

        if (knickname != null && !"".equals(knickname)) {
            reception.setKnickname(knickname);
        }
        if (snickname != null && !"".equals(snickname)) {
            reception.setSnickname(snickname);
        }
        if (stnickname != null && !"".equals(stnickname)) {
            reception.setStnickname(stnickname);
        }
        if (rkey != null && !"".equals(rkey)) {
            if (rkey.equals("1")) {
                reception.setRkey1(rkey);
            } else if (rkey.equals("2")) {
                reception.setRkey2(rkey);
            }
            reception.setRkey(rkey);
        }
        if (source != null && !"".equals(source)) {
            reception.setSource(source);
        }

        if (worth != null && !"".equals(worth)) {
            reception.setWorth(Integer.parseInt(worth));
        }
        if (phone != null && !"".equals(phone)) {
            reception.setPhone(phone);
        }
        if (email != null && !"".equals(email)) {
            reception.setEmail(email);
        }
        if (qq != null && !"".equals(qq)) {
            reception.setQq(qq);
        }
        if (time != null && !"".equals(time)) {
            reception.setTime(time);
        }

        Integer currPage = 1;
        if (vo.getCurrPage() != null && !"".equals(vo.getCurrPage())) {
            currPage = vo.getCurrPage();
        }
        Integer total = receptionDao.getReceptionCount(reception);

        if (total > 500) {
            response.setContentType("text/html;charset=UTF-8");
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Cache-Control", "no-cache");
            PrintWriter out = response.getWriter();
            out.println("<script language='javascript'>");
            out.println("alert('导出的数据过多,请控制在500条之内!')");
            out.println("history.go(-1)");
            out.println("</script>");
            out.flush();
            out.close();
            out = null;
            return null;
        }
        Page page = PageUtil.createPage(total, currPage, total);
        List<TgReception> list = receptionDao.getReceptionByType(reception, page);
        Gson gson = new Gson();
        if (list != null && list.size() > 0) {
            TgTracking tracking = new TgTracking();
            for (TgReception rece : list) {
                //跟踪条数
                tracking.setClient(rece.getClient());
                List<TgTracking> listsize = trackingDao.findByExample(tracking);
                rece.setTracksize(listsize.size() + "");

                //日期转换
                if (rece.getDate() != null && !"".equals(rece.getDate())) {
                    String gtime = sdf.format(new Date(rece.getDate() * 1000));
                    rece.setGtime(gtime);
                }
                //联系方式
                if (rece.getPhone() != null && !"".equals(rece.getPhone())) {
                    if (rece.getPhone().contains("[{")) {
                        List<Phone> phone1 = gson.fromJson(rece.getPhone(),
                                new TypeToken<List<Phone>>() {
                                }.getType());
                        rece.setPhlist(phone1);
                    }
                }
                if (rece.getWorth() == 1) {
                    rece.setWorthString("维持客情");
                } else if (rece.getWorth() == 2) {
                    rece.setWorthString("长期跟踪");
                } else if (rece.getWorth() == 3) {
                    rece.setWorthString("计划跟踪");
                } else if (rece.getWorth() == 4) {
                    rece.setWorthString("随后回访跟踪");
                } else if (rece.getWorth() == 5) {
                    rece.setWorthString("必须跟踪争取");
                } else if (rece.getWorth() == 6) {
                    rece.setWorthString("已成交 实际金额" + rece.getMoney() + (rece.getMoney1() != null ? rece.getMoney1() : 0));
                }


                //学生信息
                TgClient client = new TgClient();
                client.setKeyname(rece.getClient());
                List<TgStudent> stuList = null;

                List<TgClient> cliList = clientDao.findByExample(client);
                if (cliList != null && cliList.size() > 0) {
                    TgStudent stu1 = new TgStudent();
                    stu1.setPkey(cliList.get(0).getKeyname());
                    stuList = studentDao.findByExample(stu1);

                    String student = rece.getStudent();
                    if (student != null && !"".equals(student)) {
                        try {
                            JsonValidator json = new JsonValidator();
                            Boolean flag = json.validate(student);
                            String ObjContent = "";
                            if (flag) {
                                ObjContent = student;
                            } else {
                                byte[] bytes = StringUtil.hexDecode(student);
                                ObjContent = new String(bytes, "UTF-8");
                            }
                            if (ObjContent.contains("key")) {
                                JSONObject obj = new JSONObject(ObjContent);
                                List<StuMsg> smlist = new ArrayList<StuMsg>();
                                if (stuList != null && stuList.size() > 0) {
                                    for (TgStudent s : stuList) {
                                        JSONObject obj2 = null;
                                        if (ObjContent.contains("\"key\":\"" + s.getKeyname() + "\"")) {
                                            obj2 = obj.getJSONObject(s.getKeyname());
                                        }
                                        if (obj2 != null) {
                                            StuMsg stuMsg = new StuMsg();
                                            stuMsg.setKeyname(obj2.getString("key"));
                                            stuMsg.setMoneylog(obj2.getString("moneylog"));
                                            stuMsg.setPrice(obj2.getString("price"));
                                            stuMsg.setReason(obj2.getString("reason"));
                                            stuMsg.setResult(obj2.getString("result"));
                                            stuMsg.setTestuser(s.getNickname());
                                            smlist.add(stuMsg);
                                        }
                                        rece.setSmlist(smlist);
                                    }
                                }
                            }


                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
            }

            // 创建HSSFWorkbook对象(excel的文档对象)
            HSSFWorkbook wb = new HSSFWorkbook();
            // 建立新的sheet对象（excel的表单）
            HSSFSheet sheet = wb.createSheet("调查问卷");
            // 在sheet里创建第一行，参数为行索引(excel的行)，可以是0～65535之间的任何一个
            HSSFRow row1 = sheet.createRow(0);
            row1.setHeight((short) 500);
            HSSFCellStyle style = wb.createCellStyle();
            style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
            HSSFFont font = wb.createFont();
            style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
            style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
            font.setFontName("微软雅黑");
            font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); // 字体增粗
            font.setFontHeightInPoints((short) 18);// 设置字体大小
            style.setFont(font);
            sheet.setColumnWidth(0, 15 * 256);
            CellStyle style2 = wb.createCellStyle();
            style2.setAlignment(HSSFCellStyle.ALIGN_CENTER);
            HSSFFont font2 = wb.createFont();
            style2.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
            style2.setAlignment(HSSFCellStyle.ALIGN_CENTER);
            font2.setFontName("微软雅黑");
            font2.setFontHeightInPoints((short) 12);// 设置字体大小
            style2.setFont(font2);
            style2.setWrapText(true);// 设置自动换行
            // 在sheet里创建第二行
            HSSFRow row2 = sheet.createRow(0);
            row2.setHeightInPoints(50);
            row2.createCell(0).setCellValue("  客户姓名  ");
            row2.createCell(1).setCellValue("  接待日期  ");
            row2.createCell(2).setCellValue("  接待老师  ");
            row2.createCell(3).setCellValue("  联系方式  ");
            row2.createCell(4).setCellValue("  测评中心  ");
            row2.createCell(5).setCellValue("继续跟踪价值");
            row2.createCell(6).setCellValue("    学员    ");
            row2.createCell(7).setCellValue("    报价    ");
            row2.createCell(8).setCellValue("    金额    ");

            for (int i = 0; i < 9; i++) {
                if (row2.getCell(i) != null) {
                    row2.getCell(i).setCellStyle(style2);
                }

            }
            CellStyle style3 = wb.createCellStyle();
            style3.setAlignment(HSSFCellStyle.ALIGN_CENTER);
            HSSFFont font3 = wb.createFont();
            style3.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
            style3.setAlignment(HSSFCellStyle.ALIGN_CENTER);
            style3.setFont(font3);

            for (int j = 0; j < list.size(); j++) {
                sheet.setColumnWidth(j, 20 * 320);
                HSSFRow row3 = sheet.createRow(1 + j);
                row3.createCell(0).setCellValue(list.get(j).getNickname() + "");
                row3.createCell(1).setCellValue(list.get(j).getGtime() + "");
                row3.createCell(2).setCellValue(list.get(j).getReceptionns() + "");
                if (list.get(j).getPhlist() != null && list.get(j).getPhlist().get(0).getPhone() != null) {
                    if ("爸爸".equals(list.get(j).getPhlist().get(0).getName()) || "妈妈".equals(list.get(j).getPhlist().get(0).getName())) {
                        row3.createCell(3).setCellValue("电话:" + list.get(j).getPhlist().get(0).getPhone() + "关系:" + list.get(j).getPhlist().get(0).getName());
                    } else if ("".equals(list.get(j).getPhlist().get(0).getGuanxi())) {
                        row3.createCell(3).setCellValue("电话:" + list.get(j).getPhlist().get(0).getPhone() + "关系:" + list.get(j).getPhlist().get(0).getGuanxi());
                    } else {
                        row3.createCell(3).setCellValue("电话:" + list.get(j).getPhlist().get(0).getPhone() + "关系:" + list.get(j).getPhlist().get(0).getName());
                    }
                } else {
                    row3.createCell(3).setCellValue("电话:" + list.get(j).getPhone());
                }
                row3.createCell(4).setCellValue(list.get(j).getRegionns() + "");
                row3.createCell(5).setCellValue(list.get(j).getWorthString() + "");
                row3.createCell(6).setCellValue(list.get(j).getSmlist() != null ? list.get(j).getSmlist().get(0).getTestuser() + "" : "");
                row3.createCell(7).setCellValue(list.get(j).getSmlist() != null ? list.get(j).getSmlist().get(0).getPrice() + "" : "");
                row3.createCell(8).setCellValue(list.get(j).getSmlist() != null ? list.get(j).getSmlist().get(0).getMoneylog() + "" : "");

                for (int i = 0; i < 9; i++) {
                    if (row3.getCell(i) != null) {
                        row3.getCell(i).setCellStyle(style3);
                    }
                }
            }
            CellStyle style4 = wb.createCellStyle();
            style4.setAlignment(HSSFCellStyle.ALIGN_CENTER);
            HSSFFont font4 = wb.createFont();
            font4.setColor(HSSFColor.RED.index);// HSSFColor.VIOLET.index
            // //字体颜色
            style4.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
            style4.setAlignment(HSSFCellStyle.ALIGN_CENTER);
            style4.setFont(font4);
            style4.setWrapText(true);// 设置自动换行
            // 输出Excel文件
            OutputStream output = response.getOutputStream();
            response.reset();
            response.setHeader(
                    "Content-disposition",
                    "attachment;filename="
                            + URLEncoder.encode("调查问卷.xls", "UTF-8"));
            response.setContentType("application/msexcel;charset=UTF-8");
            wb.write(output);
            output.close();

        }
        return null;
    }

    /**
     * @Description:下载（导出Excel）
     * @author: Hqd
     * @date: 2017年11月7日 下午3:25:58 
     * @return
     */
    @RequestMapping(value = "/uploadWeekToExcel")
    public void uploadWeekToExcel(final BaseVo vo, final HttpServletRequest request, final HttpServletResponse response)
            throws Exception {
        String monday = request.getParameter("startTime");
        String sunday = request.getParameter("endTime");
        if (StringUtil.isEmpty(monday) || StringUtil.isEmpty(sunday)) {
            //获取当前日期的一周
            Calendar cal = Calendar.getInstance();
            cal.setTime(new Date());
            int d = 0;
            if (cal.get(Calendar.DAY_OF_WEEK) == 1) {
                d = -6;
            } else {
                d = 2 - cal.get(Calendar.DAY_OF_WEEK);
            }
            cal.add(Calendar.DAY_OF_WEEK, d);
            //所在周开始日期
            monday = new SimpleDateFormat("yyyy-MM-dd").format(cal.getTime());
            cal.add(Calendar.DAY_OF_WEEK, 6);
            //所在周结束日期
            sunday = new SimpleDateFormat("yyyy-MM-dd").format(cal.getTime());
        }
        List<TgOffice> list = tgOfficeDao.findByExample(new TgOffice());
        // 创建HSSFWorkbook对象(excel的文档对象)
        WriterExcel.uploadWeekToExcel(monday, sunday, list, moneyDao, response);
    }

    //未打分统计  
    @RequestMapping(value = "/markstatis")
    public ModelAndView markstatis(ModelMap modelMap, final BaseVo vo,
          final HttpServletRequest request, final HttpServletResponse response)
            throws Exception {
        modelMap = WebExecutor.execute(logger, vo, new Biz() {
            public Result process() {
                Result result = new ResultSupport(true);
  				String date = request.getParameter("date");
  				
  				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
  				if(date==null || date.equals("")){
  					date = sdf.format(new Date());
  				}
  				
  				List<GradeSta> list = new ArrayList<GradeSta>();
  				TgUsergrade ugrade = new TgUsergrade();
  				TgUserinfo user1 = new TgUserinfo();
  				TgUser user3 = new TgUser();
  				TgUser user4 = new TgUser();
            	TgUser user = new TgUser();
                user1.setType(1); //太优的中心主任
                List<TgUserinfo> uList = userinfoDao.getUserInfoByUserInfo(user1);
                user1.setType(2);//竞思的区域监管
                uList.addAll(userinfoDao.getUserInfoByUserInfo(user1));
                if(uList!=null && uList.size()>0){
                	TgUsernames usernames = new TgUsernames();
                	for(TgUserinfo u:uList){
                		GradeSta grade = new GradeSta();
                		grade.setCenter(u.getRegions());
                		grade.setNickname(u.getNickname());
                		if(u.getType()==1){
                			grade.setType("中心主任");
  	  						user3.setJob("课程顾问");
  	  						user3.setTypes("排除销售主管");
  	  						user3.setIs_zhuanz("排除未转正");
  	  						user3.setRegion(u.getRegion());
  	  						List<TgUser> uList2 = userDao.getUserInfoByType2(user3);
  	  						//专门查询两位使用OA系统的中心主任有没有给行政老师打分
  	  						String msg = "";
  	  						ugrade.setDate(date);
  	  						if(u.getNickname().equals("佘晴")){
  	  							ugrade.setAdd_username(u.getUsername());
	  	  						ugrade.setUsername("wanfei");
	    						if(usergradeDao.countEqual(ugrade)==0L){
	    							ugrade.setUsername("万菲");
	    							msg +=u.getNickname()+"未给"+ugrade.getUsername()+"打分<br/>";
	    						}
  	  						}else if(u.getNickname().equals("刘国超")){
  	  							ugrade.setAdd_username(u.getUsername());
	  	  						ugrade.setUsername("wanfei");
	    						if(usergradeDao.countEqual(ugrade)==0L){
	    							ugrade.setUsername("万菲");
	    							msg +=u.getNickname()+"未给"+ugrade.getUsername()+"打分<br/>";
	    						}
  	  						}else{
  	  							
  	  						}
  	  						grade.setMsg(msg);
  	  						
                			if(uList2!=null && uList2.size()>0){
                				for(TgUser u2:uList2){
                					ugrade.setDate(date);
                					ugrade.setAdd_username(u.getUsername());
                					ugrade.setUsername(u2.getUsername());
                					if(usergradeDao.countEqual(ugrade)==0L){
                						msg +=u.getNickname()+"未给"+u2.getNickname()+"打分<br/>";
                					}
                				}
                				grade.setMsg(msg);
                			}
                		}else if(u.getType()==2){
                			grade.setType("销售主管");
                			
                			usernames.setUsername(u.getUsername());
                			usernames.setDate(date);
                			List<TgUsernames> uList2 = usernamesDao.findByExample(usernames);
                			if(uList2!=null && uList2.size()>0){
                				String[] users = uList2.get(0).getUsernames2().split(",");
                				if(users!=null && users.length>0){
                					String msg = "";
                					for(int i=0;i<users.length;i++){
                						ugrade.setDate(date);
                    					ugrade.setAdd_username(u.getUsername());
                    					ugrade.setUsername(users[i]);
                    					if(usergradeDao.countEqual(ugrade)==0L){
                    						if(users[i]!=null && !"".equals(users[i])){
                    							user.setUsername(users[i]);
                        						user.setIs_zhuanz("排除未转正");
                        						TgUser us =userDao.getUserInfoByType(user);
                        						if(us!=null){
                        							msg +=u.getNickname()+"未给"+us.getNickname()+"打分<br/>";
                        						}
                    						}
                    					}
                					}
                					grade.setMsg(msg);
                				}
                			}
                		}
                		list.add(grade);
                	}
                }
                
                try {
	                String url = "http://www.yueqiao.org/web/teaweb/getTeacherList2.json?position=1";
	                String teacher = HttpUtil.doGet(url, "", "utf-8", true);
	                JSONObject obj = new JSONObject(teacher);
	                JSONArray listobj = obj.getJSONArray("list");
	                List<TgUser> tlist = new ArrayList<TgUser>();
	                for (int i = 0; i<listobj.length(); i++) {
	                    TgUser tuser = new TgUser();
	                    JSONObject o = new JSONObject(listobj.get(i).toString());
	                    if(!o.isNull("name")){
	                    	tuser.setNickname(o.getString("name"));
	                    }
	                    if(!o.isNull("login_name")){
	                    	tuser.setUsername(o.getString("login_name"));
	                    }
	                    if(!o.isNull("center")){
	                    	tuser.setRegion(o.getString("center"));
	                    }
	                    if(!o.isNull("xz_name")){
	                    	tuser.setRegions(o.getString("xz_name"));
	                    }
	                    if(!o.isNull("xz_nickname")){
	                    	tuser.setSuperhash(o.getString("xz_nickname"));
	                    }
	                    tlist.add(tuser);
	                }
	                
	                if(tlist!=null && tlist.size()>0){
	                	for(TgUser tu:tlist){
	                		GradeSta grade = new GradeSta();
	                		String center = tu.getRegion();
	                		grade.setType("中心主任");
	                		grade.setCenter(center);
	                		if(center==null || center.equals("") || center.equals("null")){
	                			center = "";
	         			   	}else{
	         			   		if(center.equals("成都桐梓林中心")){
	         			   			center = "成都桐梓(zǐ)林中心";
	         			   		}else if(center.equals("广州区庄中心")){
	         			   			center = "广州区(ōu)庄中心";
	         			   		}
	         			   	}
	                		grade.setNickname(tu.getNickname());
	                		user4.setJob("课程顾问");
  	  						user4.setTypes("排除销售主管");
  	  						user4.setIs_zhuanz("排除未转正");
  	  						user4.setRegions(center);
  	  						List<TgUser> uList2 = userDao.getUserInfoByType2(user4);
	     	                
	     	                String msg="";
	     	                for (int i = 0; i<uList2.size() ; i++) {
     	            		   ugrade.setDate(date);
	     	            	   ugrade.setAdd_username(tu.getUsername());
	     	            	   ugrade.setUsername(uList2.get(i).getUsername());
	     	            	   if(usergradeDao.countEqual(ugrade)==0L){
	     	            		   msg +=tu.getNickname()+"未给"+uList2.get(i).getNickname()+"打分<br/>";
	     	            	   }
	     	               	}
	     	                if(tu.getSuperhash()!=null && tu.getSuperhash()!="" && !"null".equals(tu.getSuperhash())){
	     	                	ugrade.setDate(date);
		     	                ugrade.setUsername(tu.getSuperhash());
		     	                ugrade.setAdd_username(tu.getUsername());
		     	                if(usergradeDao.countEqual(ugrade)==0L){
		     	                	msg +=tu.getNickname()+"未给"+tu.getRegions()+"打分<br/>";
		     	                }
	     	                }
	     	                grade.setMsg(msg);
	     	                list.add(grade);
	                	}
	                }
                } catch (Exception e) {
					e.printStackTrace();
				}
                
				result.setDefaultModel("list", list);
				result.setDefaultModel("date", date);
                return result;
            }
        });
        return new ModelAndView("consultant/mark/markstatis", modelMap);
    }
    
    //跳到400电话号码添加
    @RequestMapping(value = "/dhzy_phone_add")
    public ModelAndView dhzy_phone_add(ModelMap modelMap, final BaseVo vo,
            final HttpServletRequest request, final HttpServletResponse response)
            throws Exception {
        modelMap = WebExecutor.execute(logger, vo, new Biz() {
            public Result process() {
                Result result = new ResultSupport(true);
                TgUser user = UserUtil.getUserFromCookies();
                if(user != null ){
                	result.setDefaultModel("user", user.getUsername());
                }
                List<TgOffice> offList = tgOfficeDao.findAll(TgOffice.class);
                result.setDefaultModel("cenList", offList);
                return result;
            }
        });
        return new ModelAndView("consultant/dhzy_phone_add", modelMap);
    }
    
    //400电话号码保存
    @RequestMapping(value = "/dhzy_phone_save")
    public ModelAndView dhzy_phone_save(ModelMap modelMap, final BaseVo vo,final HttpServletRequest request, HttpServletResponse response)
            throws BaseException {
        modelMap = JsonExecutor.execute(logger, vo, new JsonBiz() {
            public Result process() {
                Result result = new ResultSupport(true);
                TgUser user = UserUtil.getUserFromCookies();
	                String id = request.getParameter("id");				
	     //         String keyname = request.getParameter("keyname");		//唯一标识号
	                String username = request.getParameter("username");		//400电话接听的老师
	                String ld_phone = request.getParameter("ld_phone");		//来电号码
	                String phone = request.getParameter("phone");			//家长留存号码
	                String nickname = request.getParameter("nickname");		//家长姓名，无则为匿名
	                String ld_time = request.getParameter("ld_time");		//来电时间
	                String provice = request.getParameter("province");		//省会
	                String city = request.getParameter("city");				//城市
	                String region_p = request.getParameter("region_p");		//400电话所属中心
	                String type_ph = request.getParameter("type_ph");		//1，当地有中心家长电话，2，当地无中心的家长电话，3，广告加盟合作求职电话，4.接通挂断、无回应、还未回拨的电话
	                String yuy_cause = request.getParameter("yuy_cause");	//未预约原因
	                String yuy_type = request.getParameter("yuy_type");		//是否预约：1是，2否，默认为0，无状态
	                String state = request.getParameter("state");			//1:未接通、 2：已接电话,0：无状态
	                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
	                Date cdate = null;
					try {
						cdate = sdf.parse(sdf.format(new Date()));			//提交创建日期
					} catch (ParseException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}											
	                Tgld_phone tgldphone = new Tgld_phone();
	                if(username != null && !"".equals(username)){
	                	tgldphone.setUsername(username);
	                }
	                if(ld_phone != null && !"".equals(ld_phone)){
	                	tgldphone.setLd_phone(ld_phone);
	                }
	                if(phone != null && !"".equals(phone)){
	                	tgldphone.setPhone(phone);
	                }
	                if(nickname != null && !"".equals(nickname)){
	                	tgldphone.setNickname(nickname);
	                }else{
	                	tgldphone.setNickname("匿名");
	                }
	                if(ld_time != null && !"".equals(ld_time)){
	                	tgldphone.setLd_time(ld_time);
	                }
	                if(provice != null && !"".equals(provice)){
	                	tgldphone.setProvice(provice);
	                }
	                if(city != null && !"".equals(city)){
	                	tgldphone.setCity(city);
	                }
	                if(region_p != null && !"".equals(region_p)){
	                	tgldphone.setRegion_p(region_p);
	                }
	                if(type_ph != null && !"".equals(type_ph)){
	                	tgldphone.setType_ph(type_ph);
	                }
	                if(yuy_cause != null && !"".equals(yuy_cause)){
	                	tgldphone.setYuy_cause(yuy_cause);
	                }
	                if(yuy_type != null && !"".equals(yuy_type)){
	                	tgldphone.setYuy_type(yuy_type);
	                }
	                if(state != null && !"".equals(state)){
	                	tgldphone.setState(state);
	                }
	                if(cdate != null && !"".equals(cdate)){
	                	tgldphone.setCdate(cdate);
	                }
	                tgClientPhoneDao.saveOrUpdate1(tgldphone);
                return result;
            }
        });
        return new ModelAndView("", modelMap);
    }
    

    //400电话统计
    @RequestMapping(value = "/dhzy_phone")
    public ModelAndView dhzy_phone(ModelMap modelMap, final BaseVo vo,
    		final HttpServletRequest request, final HttpServletResponse response)
    				throws Exception {
    	modelMap = WebExecutor.execute(logger, vo, new Biz() {
    		public Result process() {
    			Result result = new ResultSupport(true);
    			try {
    				TgClient client = new TgClient();
    		//		String date = request.getParameter("date");
    		//		String lianxi_name = request.getParameter("lianxi_name");
    				String ld_phone = request.getParameter("ld_phone");
    		//		String username = request.getParameter("username");
    	 	//		String type_ph = request.getParameter("type_ph");
    				String stardate = request.getParameter("stardate");
    				String enddate = request.getParameter("enddate");
    				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    				
    				TgUser user = UserUtil.getUserFromCookies();
    				if (user != null && user.getId()== 649 || user.getUsername()=="system" || user.getId()== 648) {
    				if(ld_phone!=null && !ld_phone.equals("")){
    					client.setPhone(ld_phone);
    				}
    				if(stardate!=null && !stardate.equals("")){
    					client.setsTime(stardate);
                        Date date1 = sdf.parse(stardate);
                        client.setStartTime(date1.getTime() / 1000);
    				}else{
    				
    				}
    				if(enddate!=null && !enddate.equals("")){
    					client.setsTime(enddate);
                        Date date1 = sdf.parse(enddate);
                        client.setEndTime(date1.getTime() / 1000);
    				}else{
    				
    				}
    				Integer currPage = 1;
    				if (vo.getCurrPage() != null && !"".equals(vo.getCurrPage())) {
    					currPage = vo.getCurrPage();
    				}
    				Integer total = clientDao.getClientCountImpCBySource(client);
    				Page page = PageUtil.createPage(20, currPage, total);
    				List<TgClient> list = clientDao.getClientListImpBySource(client, page);
    				
    				result.setDefaultModel("list", list);
    				result.setDefaultModel("page", page);
    				result.setDefaultModel("currPage", currPage);
    				result.setDefaultModel("stardate", stardate);
    				result.setDefaultModel("enddate", enddate);
    				}else{
    					return result;
    				}
    			} catch (Exception e) {
    				e.printStackTrace();
    			}
    			return result;
    		}
    	});
    	return new ModelAndView("consultant/dhzy_phone_list", modelMap);
    }
    
}
